js中filter用法总结

发布于 分类 vue标签

0311lc.com说:

基本用法

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}]

进阶用法

  • 数组去重(有点过时)
let arr = [1, 2, 3, 2, 3, 4]
let arrFilter = arr.filter((ele, index, arr) => {
  return arr.indexOf(ele) === index
})
console.log(arrFIlter)
let arr = [1, 2, 3, 2, 3, 4]
let arrFilter = [...new Set(arr)]
console.log(arrFilter)

目前比较常用的方法是使用ES6的set完成,上面

  • 数组中的空字符去除
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']

https://juejin.cn/post/6844903551886426119


发表评论

电子邮件地址不会被公开。 必填项已用*标注