filter过滤
简单讲filter就是一个数组过滤器,参数接收一个函数,数组的每一项经过函数过滤,返回一个符合过滤条件的新数组
基本用法
let arr = [1, 3, 5, 8]
let arrFilter = arr.filter(ele => ele > 4)
console.log(arrFilter) // [5, 8]
用来过滤对象数组中符合条件的对象
let arrObj = [{
name: 'aa', age: 13
}, {
name: 'bb', age: 23
}, {
name: 'cc', age: 18
}, {
name: 'dd', age: 11
}, {
name: 'ee', age: 28
}]
let arrObjFilter = arrObj.filter(ele => ele.age > 18)
console.log(arrObjFilter) // [{name: 'bb', age: 23}, {name: 'ee', age: 28}]
数组去重(有点过时)
item (当前遍历的数组项)
index(当前项索引)
arr (调用filter数组本身)
let arr = [1, 2, 3, 2, 3, 4]
let arrFilter = arr.filter((item, index, arr) => {
return arr.indexOf(ele) === index
})
console.log(arrFIlter)
目前比较常用的方法是使用ES6的set完成(去重)
let arr = [1, 2, 3, 2, 3, 4]
let arrFilter = [...new Set(arr)]
console.log(arrFilter)
数组中的空字符去除
let arr = ['1', '2', '3', '', null, undefined, ' ', '4']
let arrFilter = arr.filter((ele, index, arr) => {
return ele && ele.trim()
})
console.log(arrFIlter)
结合map使用可以先过滤出符合条件的对象然后去除某些不需要的字段
// 需求: 年龄大于18的姓名
let arrObj = [{
name: 'aa', age: 13
}, {
name: 'bb', age: 23
}, {
name: 'cc', age: 18
}, {
name: 'dd', age: 11
}, {
name: 'ee', age: 28
}]
let arrObjFilter = arrObj.filter(ele => ele.age > 18).map(ele => {
return ele.name
})
console.log(arrObjFilter) // ['bb', 'ee']