map():
Different from forEach and other traversal methods, the return statement has no effect in forEach. Map can change the value of the current loop and return a new array after the changed value (map needs return), which is generally used to process the value of an array to be modified.
let arr1 = [1,2,3]; let arr2 = 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] [1,2,3] return value * value; }) console.log(arr1); // [ 1, 2, 3 ] console.log(arr2); // [ 1, 4, 9 ]
filter():
The filter function can be seen as a filter function that returns an array of qualified elements
The filter needs to judge whether it is true or false when it is looping. Only true can return this element;
let arr1 = [1,2,3]; let arr2 = arr1.filter((value,key,arr) => { console.log(value) // 1,2,3 console.log(key) // 0,1,2 console.log(arr) // [1,2,3] return value >= 3 ? false : true; }) console.log(arr1); // [ 1, 2, 3 ] console.log(arr2); // [ 1, 2 ]
filter() filters non conformances
let arr = [1,2,3] let newArr = arr.filter(item => item>=3) console.log(newArr)
filter() removes empty string, undefined, null
let arr = ['','1','2',undefined,'3.jpg',undefined] let newArr = arr.filter(item => item) console.log(newArr)
filter() array de duplication
let arr = [1, 2, 2, 3, 4, 5, 5, 6]; let newArr = arr.filter((x, index,self)=>self.indexOf(x)===index) console.log(newArr)
set() method is recommended for de duplication
let arr = [1, 2, 2, 3, 4, 5, 5, 6]; let newArr =Array.from(new Set(arr)) console.log(newArr)
filter() filters array objects
Single condition filter:
let arr = [ {a:'Apple',b:'bread',c:'eat'}, {a:'Banana',b:'bread',c:'Not to eat'}, {a:'Banana',b:'Apple',c:'eat'}, {a:'Apple',b:'Banana',c:'Not to eat'}, ] console.log(arr.filter(item => item.a=== 'Apple' ))//[{a: 'Apple', b: 'bread', c: 'eat'}, {a: 'Apple', b: 'Banana', c: 'don't eat'}]
Multiple criteria screening: at present, only this stupid method is thought of
let a = 'Apple'; //Filter parameter a let b = 'bread'; //Filter parameter b let c = '' //Filter parameter c let arr = [ {a:'Apple',b:'bread',c:'eat'}, {a:'Banana',b:'bread',c:'Not to eat'}, {a:'Banana',b:'Apple',c:'eat'}, {a:'Apple',b:'Banana',c:'Not to eat'}, ]; if (a != '') { arr = arr.filter(item => item.a === a) } if (b != '') { arr = arr.filter(item => item.b === b) } if (c != '') { arr = arr.filter(item => item.c === c) } console.log(arr) // Screening results: [{a: 'Apple', b: 'bread', c: 'eat'}]
Change from: https://blog.csdn.net/zuorishu/article/details/80958705
Related links: https://juejin.im/post/5b5a9451f265da0f6a036346