js中的filter过滤和排序
filter过滤对象数组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 && im()
})
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']
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论