Map reduce filter for each some every

ES6 array map, reduce,filter, forEach, some, every

catalogue

1. map

Returns a new array without changing the original array.

Corresponding parameters: the value of item each time, the current index, and the original array arr

eg.

let arr = [22, 55, 67, 33, 99, 70];
let result = arr.map((item, index, arr) => {
  return item > 60 ? "pass" : "fail,";
});
console.log(result);
console.log(arr);

['fail', 'fail', 'pass',' fail ',' fail ',' pass']
[ 22, 55, 67, 33, 99, 70 ]

2. reduce

One by one, sum or average, accumulator. Do not change the original array.
temp is the temporary variable of each time, the temporary sum of the nth and Nth + 1st times, item is the value to be added each time, index is the index of each cycle, and index starts from 0.

let arr2 = [22, 55, 67, 33, 99, 70];
let result2 = arr2.reduce((temp, item, index) => {
  console.log(temp, item, index);
  return temp + item;
});
console.log(result2);
console.log(arr2)

22 55 1
77 67 2
144 33 3
177 99 4
276 70 5
346
[ 22, 55, 67, 33, 99, 70 ]

3. filter

Returns the array elements that meet the conditions specified in the callback function. true is reserved and false is filtered.
Do not change the size of the original array.

let arr3 = [2, 4, 76, 87, 35, 66];
let result3 = arr3.filter((item) => item % 3 === 0);
console.log(result3);
console.log(arr3);

[ 87, 66 ]
[ 2, 4, 76, 87, 35, 66 ]

4. forEach iteration

forEach traverses the array without return value. It does not change the original array, but just traverses.

let arr4 = [2, 3, 4, 5];
arr4.forEach((item) => console.log(item));

2
3
4
5

5. every

Traverse each item of the array, and each item returns true, then the final result is true. When any item returns false, stop traversal and return false. Do not change the original array.

let arr5 = [1, 2, 5, 4, 5, 6, 7, 8];
let flag = arr5.every((item, index, arr) => {
  console.log(item);
  return index === 0 ? true : item > arr[index - 1];
});
console.log(flag);
console.log(arr5);

1
2
5
4
false
[ 1, 2, 5, 4, 5, 6, 7, 8 ]

6. some

When traversing each item of the array, if one item returns true, it will return true. When any item returns true, it will stop traversing and return true.

let arr6 = [1, 2, 3, 5, 6, 5, 6, 7, 8, 9];
let flag6 = arr6.some((item, index, arr) => {
  console.log(item);
  return index == 0 ? false : item < arr[index - 1];
});
console.log(flag6);
console.log(arr6);

1
2
3
5
6
5
true
[ 1, 2, 3, 5, 6, 5, 6, 7, 8, 9 ]

The above six methods are ES6 syntax, which is only supported in IE9 and above. However, the lower version of IE can be supported through babel translation.
None of the above changes the original array.

some and every return true and false.
map and filter return a new array.
reduce allows the first and second items of the array to perform some calculation and return the result of the final operation.
forEach has no return value.

Posted by DeathRipple on Wed, 11 May 2022 01:25:05 +0300