美文网首页
filter() ,

filter() ,

作者: 糖醋里脊120625 | 来源:发表于2020-06-16 16:59 被阅读0次
1/过滤对象数组中符合条件的对象

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


2/数组去重

let arr = [1, 2, 3, 2, 3, 4]
let arrFilter = arr.filter((ele, 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)



3/数组中的空字符去除

let arr = ['1', '2', '3', '', null, undefined, '  ', '4']
let arrFilter = arr.filter((ele, index, arr) => {
  return ele && ele.trim()
})
console.log(arrFIlter)




// 需求: 年龄大于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']

相关文章

网友评论

      本文标题:filter() ,

      本文链接:https://www.haomeiwen.com/subject/wyyrxktx.html