js 数组的filter方法
程序员文章站
2022-06-29 20:03:36
...
语法:
array.filter(function(currentValue,index,arr), thisValue)
- currentValue: 当前元素
- index:当前元素索引
- arr:当前元素所属数组
- thisValue:作为参数中的function中的this
实例:
var ages = [32, 33, 16, 40];
function checkAdult(age, index, arr) {
console.log(age)
console.log(index)
console.log(arr);
console.log(this);
return age >= 18;
}
var newArr = ages.filter(checkAdult, {name: 'value'})
上面例子会打印4次,数组中的每个元素都会执行checkAdult方法,this的值是传入的{name:’value’}
高级用法
我们可以这样用,如果数组是这样的
var arr = [{id:1, flag:true},{id:2,flag:false},{id:3, flag:true}]
筛选出所有的flag为false的对象
var newArr = arr.filter(obj => !obj.flag);
值得一提的是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.去掉空数组空字符串、undefined、null
var arr = ['1','2',undefined, '3.jpg',undefined]
var newArr = arr.filter(item => item)
console.log(newArr)
//输出结果 [ '1', '2', '3.jpg' ]
var arr = ['1','2',null, '3.jpg',null]
var newArr = arr.filter(item => item)
console.log(newArr)
//输出结果 [ '1', '2', '3.jpg' ]
>//空字符串里面不能包含空格
var arr = ['1','2','', '3.jpg','']
var newArr = arr.filter(item => item)
console.log(newArr)
//输出结果 [ '1', '2', '3.jpg' ]
3.去掉数组中不符合项
var arr = [20,30,50, 96,50]
var newArr = arr.filter(item => item>40)
console.log(newArr)
// 输出结果 [ 50, 96, 50 ]
4.过滤不符合项
var arr = ['10','12','23','44','42']
var newArr = arr.filter(item => item.indexOf('2')<0)
console.log(newArr)
// 输出结果 [ '10', '44' ]
5.数组去重
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]
6.数组去重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)]
7.数组对象去重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)