map():

Map is different from forEach and other traversal methods. In forEach, a return statement has no effect. Map can change the value of the current loop and return a new array with changed values (map needs to return).

letArr1 = [1, 2, 3];letArr2 = arr1.map((value,key,arr) => {console.log(value) // 1,2,3 console.log(key) // 0,1, 2 console.log(arr) //[1,2,3] [1,2,3]returnvalue * value; }) console.log(arr1); // [ 1, 2, 3 ] console.log(arr2); // [1, 4, 9]Copy the code


filter():

The filter function can be thought of as a filter function that returns an array of elements that match the criteria

Filter will return the element if it is true or false.

letArr1 = [1, 2, 3];letArr2 = arr1.filter((value,key,arr) => {console.log(value) // 1,2,3 console.log(key) // 0,1, 2 the console. The log (arr) / / [1, 2, 3]return value >= 3 ? false : true; }) console.log(arr1); // [ 1, 2, 3 ] console.log(arr2); // [1, 2]Copy the code


Filter () Filter nonconforming items:

letArr = [1, 2, 3]letnewArr = arr.filter(item => item>=3) console.log(newArr); / / [3]Copy the code


Filter () removes empty string, undefined, null:

let arr = [' '.'1'.'2',undefined,'3.jpg',undefined]
let newArr = arr.filter(item => item)
console.log(newArr) //["1"."2"."3.jpg"]Copy the code


Filter () array deduplicating:

let arr = [1, 2, 2, 3, 4, 5, 5, 6];
let newArr = arr.filter((x, index,self)=>self.indexOf(x)===index) 
console.log(newArr); //[1, 2, 3, 4, 5, 6]Copy the code


The set() method is recommended for rescheduling:

let arr = [1, 2, 2, 3, 4, 5, 5, 6];
let newArr =Array.from(new Set(arr)) 
console.log(newArr); //[1, 2, 3, 4, 5, 6]Copy the code


Filter () filters array objects

Single condition screening:

let arr = [
	    {a:'apple',b:'bread',c:'eat'},
	    {a:'banana',b:'bread',c:'don't eat'},
	    {a:'banana',b:'apple',c:'eat'},
	    {a:'apple',b:'banana',c:'don't eat'},
	  ]
console.log(arr.filter(item => item.a=== 'apple' ))//[{a:'apple',b:'bread',c:'eat'},{a:'apple',b:'banana',c:'don't eat'}]Copy the code

Multiple criteria screening: currently only think of this stupid method

let a = 'apple'; // Filter parameter Alet b = 'bread'; // Filter parameter blet c = ' '// Filter parameter clet arr = [
	    {a:'apple',b:'bread',c:'eat'},
	    {a:'banana',b:'bread',c:'don't eat'},
	    {a:'banana',b:'apple',c:'eat'},
	    {a:'apple',b:'banana',c:'don't eat'},
	  ];

arr = arr.filter(item => (a?item.a === a : true) && (b? item.b === b :true) && (c? item.c === c :true)); Console. log(arr) // Filter result: [{a:'apple',b:'bread',c:'eat'}]Copy the code