1. 程式人生 > 實用技巧 >ES6 filter() 陣列過濾、去重方法總結

ES6 filter() 陣列過濾、去重方法總結

1.建立一個數組,判斷陣列中是否存在某個值

var newarr = [
  { num: 1, val: 'ceshi', flag: 'aa' },
  { num: 2, val: 'ceshi2', flag: 'aa2'  }
]
console.log(newarr.filter(item => item.num===2 ))
//[{ num: 2, val: 'ceshi2', flag: 'aa2' }]

2.也可以通過上面方法過濾掉num為2的留下num為1的

var newarr = [
  { num: 1, val: 'ceshi', flag: 'aa' },
  { num: 2, val: 'ceshi2', flag: 'aa2'  }
]
console.log(newarr.filter(item => item.num!=2 ))

3.去掉空陣列空字串、undefined、null

var arr = ['1','2',undefined, '3.jpg',undefined]
var newArr = arr.filter(item => item)
console.log(newArr)

var arr = ['1','2',null, '3.jpg',null]
var newArr = arr.filter(item => item)
console.log(newArr)

>//空字串裡面不能包含空格
var arr = ['1','2','', '3.jpg','']
var newArr = arr.filter(item => item)
console.log(newArr)

4.去掉陣列中不符合項

var arr = [20,30,50, 96,50]
var newArr = arr.filter(item => item>40)  
console.log(newArr)

5.過濾不符合項

var arr = ['10','12','23','44','42']
var newArr = arr.filter(item => item.indexOf('2')<0) 
console.log(newArr)

6.陣列去重

var arr = [1, 2, 2, 3, 4, 5, 5, 6, 7, 7,8,8,0,8,6,3,4,56,2];
var arr2 = arr.filter((x, index,self)=>self.indexOf(x)===index)  
console.log(arr2); //[1, 2, 3, 4, 5, 6, 7, 8, 0, 56]

7.陣列去重es6

var arr=[1,2,1,'1',null,null,undefined,undefined,NaN,NaN]
let res=Array.from(new Set(arr));//{1,2,"1",null,undefined,NaN}
//or
let newarr=[...new Set(arr)]

8.陣列物件去重es6

let person = [
     {id: 0, name: "小明"},
     {id: 1, name: "小張"},
     {id: 2, name: "小李"},
     {id: 3, name: "小孫"},
     {id: 1, name: "小周"},
     {id: 2, name: "小陳"},  
];
 
let obj = {};
 
let peon = person.reduce((cur,next) => {
    obj[next.id] ? "" : obj[next.id] = true && cur.push(next);
    return cur;
},[]) //設定cur預設型別為陣列,並且初始值為空的陣列
console.log(peon);
// (4) [{…}, {…}, {…}, {…}]0: {id: 0, name: "小明"}1: {id: 1, name: "小張"}2: {id: 2, name: "小李"}3: {id: 3, name: "小孫"}length: 4__proto__: Array(0)