1,来一个最简单最常用的栗子:
获得年龄为9岁的孩子
1 let arr = [
2 {
3 name:'小明',
4 sex:0,
5 age:9
6 },
7 {
8 name:'小红',
9 sex:1,
10 age:9
11 },
12 {
13 name:'小亮',
14 sex:0,
15 age:10
16 }
17 ]
18 console.log(arr.filter(item => item.age === 9));
结果为:[ { name: '小明' , sex: 0, age: 9 }, { name:'小红' , sex: 1, age: 9 } ]
filter方法的返回值为符合过滤条件的元素;
2,去掉数组空字符串、undefined、null
1 let arr2 = [ 1,3,5,null,4,undefined,10,'hahah','','end' ];
2
3 console.log(arr2.filter(item => item));
结果为:[1, 3, 5, 4, 10, "hahah", "end"]
3,数组去重的用法
1 let arr3 = [ 1,3,3,6,5,5,8,9,8,'hahah','wer','hahah' ];
2 console.log(arr3.filter((item,index,self) => self.indexOf(item) == index));