ES6 map and filter

ES6 map and filter

1、map

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 ]

2、filter

filter filtering function will return the right array elements.

of arr1 = the let [l, 2,3 ]; 
the let arr2 is = arr1.filter ((value, Key, ARR) => { 
    the console.log (value)     // l, 2,3 
    the console.log (Key)       // 0 , 1, 2 
    console.log (arr)       // [, 2, 3] 
    return value> = 3? false : to true ;      // Interconnect is the value> = 3 it was established, the establishment of the part of the return, not part of the establishment does not return. 
}) 
the console.log (of arr1); // [. 1, 2,. 3] 
the console.log (arr2 is); // [. 1, 2]
  • Screening of eligible items
// Returns an array of 2 or greater new array 
console.log ( "-------------- screened (greater than or equal to 2) ------------ ----------- ") 
the let ARR = [. 1, 2,. 3] 
the let newArr = arr.filter (Item => Item> = 2) 
the console.log (newArr)

  

  • Deduplication Array
let arr5 = [1, 2, 2, 3, 4, 5, 5, 6];
let newArr4 = arr5.filter((x, index, self) => {
    return self.indexOf(x) === index
})
console.log(newArr4) //[1,2,3,4,5,6]

  

  • Remove empty string, undefined, null
// filter () to remove the empty string, undefined, null 
the let arr4 = [ '', '. 1', '2', undefined, '3.jpg', undefined] 
the let newArr3 = arr4.filter (Item => Item) 
console.log (newArr3); // [ ' 1', '2', '3.jpg']

  

  • Screening array of objects
ARR = the let [ 
    {A: 'apple', b: 'bread', c: 'eat'}, 
    {A: 'banana', b: 'bread', c: 'eat'}, 
    {A: 'Banana ', b:' apple ', c:' eat '}, 
    {A:' apple ', b:' banana ', c:' eat '}, 
] 
 the let newarr8 arr7.filter = ((value, index, ARR ) => { 
				   return value.a = 'apple'! 
			 }) 
 the console.log (newarr8) // [{A: 'banana', b: 'bread', c: 'eat'}, {a: 'banana ', b:' apple ', c:' eat '}]

  

let a = 'apple'; // filter parameter A 
the let B = 'bread'; // filter parameter B 
the let C = '' // filter parameter C 
the let ARR = [ 
    {A: 'apple', b: 'bread' , c: 'eat'}, 
    {A: 'banana', b: 'bread', c: 'eat'}, 
    {A: 'banana', b: 'apple', c: 'eat'}, 
    { a: 'apple', b: 'banana', c: '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) 
} 
the console.log (ARR) // filter results: [{a: 'apple', b: 'bread', c: 'eat'}]

  

 

Guess you like

Origin www.cnblogs.com/BillyYoung/p/11323459.html