Home  >  Article  >  Web Front-end  >  How to implement the es6 filter() method? Usage introduction

How to implement the es6 filter() method? Usage introduction

青灯夜游
青灯夜游forward
2020-07-28 17:21:582721browse

How to implement the es6 filter() method? Usage introduction

The filter() method creates a new array, and the elements in the new array are checked for all elements in the specified array that meet the conditions.

es6 Usage of filter() method

1. Create an array and determine whether a certain value exists in the array

var newarr = [
  { num: 1, val: 'ceshi', flag: 'aa' },
  { num: 2, val: 'ceshi2', flag: 'aa2'  }
]
console.log(newarr.filter(item => item.num===2 ))

2. Remove empty spaces Array empty string, undefined, null

var arr = ['1','2',undefined, '3.jpg',undefined]
var newArr = arr.filter(item => item)
console.log(newArr)

var arr = ['1','2',null, '3.jpg',null]
var newArr = arr.filter(item => item)
console.log(newArr)

//空字符串里面不能包含空格
var arr = ['1','2','', '3.jpg','']
var newArr = arr.filter(item => item)
console.log(newArr)

3. Remove non-conforming items in the array

var arr = [20,30,50, 96,50]
var newArr = arr.filter(item => item>40)  
console.log(newArr)

4. Filter non-conforming items

var arr = ['10','12','23','44','42']
var newArr = arr.filter(item => item.indexOf(&#39;2&#39;)<0) 
console.log(newArr)

5. Array deduplication

var arr = [1, 2, 2, 3, 4, 5, 5, 6, 7, 7,8,8,0,8,6,3,4,56,2];
var arr2 = arr.filter((x, index,self)=>self.indexOf(x)===index)  
console.log(arr2); //[1, 2, 3, 4, 5, 6, 7, 8, 0, 56]

Recommended tutorial: "JavaScript Video Tutorial"

The above is the detailed content of How to implement the es6 filter() method? Usage introduction. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete