JS - ES6 filter() 筛选

 
* filter 不会改变原数组,不会对空数组进行检查

筛选符合条件项 
  var arr = ['10','12','23','44','42']
  var newArr = arr.filter( (val) => val>30 ) 
  console.log(newArr); // ["44", "42"]

 

去掉数组非真值( undefined, null, false, ' ', 0 )
  var arr = [ '1', ' ', undefined, 2, null, '', 3, false, 0, true ];
  var newArr = arr.filter( (val)=> val )
  console.log(newArr); //  ["1", " ", 2, 3, true]
  // 空字符串不包含空格

 

数组去重

  var arr = [ 1, 2, 3, 4, 1, 1, 2, 2, 3, 3, 4, 4, "a", "b", "c", "a", "b", "b" ];
  var newArr = arr.filter( (val, index, arr) => arr.indexOf(val) === index );
  console.log(newArr); // [1, 2, 3, 4, "a", "b", "c"]

 

根据数组对象中某个值进行查找

  var arr = [
    { id:1, name:"abc", val:"aaa" },
    { id:2, name:"asd", val:"bbb" },
    { id:3, name:"qwe", val:"ccc" },
  ]
  var newArr = arr.filter( (val) => val.id === 1 );
  console.log(newArr); // [{id: 1, name: "abc", val: "aaa"}]

 

posted @ 2020-10-20 16:21  sanyekui  阅读(1788)  评论(0编辑  收藏  举报