New features of ES6 array (map, filter, forEach, reduce)

Posted by gpittingale on Tue, 31 Dec 2019 07:17:40 +0100

Map: how many arrays are there? There are still so many after map processing. Parameters: item, index, array

let arr = [12,35,56,79,56];
let arr1 = arr.map(item => item%2 === 0 ? 'even' : 'odd');
let arr2 = arr.map((item,index) => index + ':' + item);

console.log(arr);  // [ 12,     35,      56,    79,     56     ]
console.log(arr1); // ['even', 'odd', 'even', 'odd', 'even']
console.log(arr2); // [ '0:12', '1:35', '2:56', '3:79', '4:56' ]

Filter: filter out unqualified ones. Parameters: item, index, array

let arr = [12,75,56,79,56];
let arr1 = arr.filter(item => item>=60);
console.log(arr);  // [ 12, 75, 56, 79, 56 ]
console.log(arr1); // [ 75, 79 ]

forEach: traversal. Just loop, no return value, and will not change the original array. Parameters: item, index, array

let arr = [12,35,56,79,56];
let arr1 = arr.forEach(item => item+20);
console.log(arr);  // [12,35,56,79,56]
console.log(arr1); // undefined

reduce: summary. tmp in the following code can be understood as the previous value.

let arr = [12,35,56,79,56];
let avg = arr.reduce((tmp,item,index) => {
  tmp += item;
  if(index === arr.length-1) tmp /= (index+1);
  return tmp;
})
console.log(avg); // 47.6 is the average of the five numbers

There are actually five parameters of reduce, tmp, item, index, array, init. If init is not passed in, the initial value will take the first value of the array, and the index starts from 1 when it is called internally.

let arr = [12,35,56,79,56];
let avg = arr.reduce((tmp,item,index,array) => {
  console.log(tmp,item,index,array);
  tmp += item;
  if(index === arr.length-1) {
    console.log('I asked for an average');
    tmp /= (index+1);
  }
  return tmp;
})
console.log(avg);

/*
  12 35 1 [ 12, 35, 56, 79, 56 ]
  47 56 2 [ 12, 35, 56, 79, 56 ]
  103 79 3 [ 12, 35, 56, 79, 56 ]
  182 56 4 [ 12, 35, 56, 79, 56 ]
  I asked for an average
  47.6
 */

If an initial value of 10000 is passed in, the index starts at 0. The initial value of tmp is 10000, and the result is naturally different.

let arr = [12,35,56,79,56];
let avg = arr.reduce((tmp,item,index,array) => {
  console.log(tmp,item,index,array);
  tmp += item;
  if(index === arr.length-1) {
    console.log('I asked for an average');
    tmp /= (index+1);
  }
  return tmp;
}, 10000)
console.log(avg);

/*
  10000 12 0 [ 12, 35, 56, 79, 56 ]
  10012 35 1 [ 12, 35, 56, 79, 56 ]
  10047 56 2 [ 12, 35, 56, 79, 56 ]
  10103 79 3 [ 12, 35, 56, 79, 56 ]
  10182 56 4 [ 12, 35, 56, 79, 56 ]
  I asked for an average
  2047.6
 */