Detailed explanation of reduce method in JavaScript

definition

1. The reduce() method receives a function as an accumulator, and each value in the array (from left to right) starts to be reduced and finally calculated as a value.

2. reduce() can be used as a higher-order function for function compose

3. reduce() will not execute the callback function for empty arrays

grammar

array.reduce(function(prev, currentValue, currentIndex, arr), initialValue)

The reduce function receives two parameters, one is the callback function and the other is the initial assignment

The callback function of the first parameter receives four parameters, which are (initial value or return value after calculation, current element, index of current element, array object to which the current element belongs)

The second parameter is the initial value passed to the function, not required

prev: the initial value passed in by the function or the return value of the last callback

currentValue: the currently processed element value in the array

currentIndex: current element index

arr: the array itself to which the current element belongs

initialValue: the initial value passed to the function

browser support

Support mainstream browsers such as Google, Firefox, ie9 and above

Example 1

var arr = [1, 2, 3, 4];
var sum = arr.reduce(function (prev, cur, index, arr) {
  console.log(prev, cur, index);
  return prev + cur;
});
console.log(arr, sum);

At this time, no initial value is assigned to prev

In the above example, the index starts from 1, the value of the first prev is the first value of the array, the value of the first cur is the second value of the array, the length of the array is 4, and the reduce function loops 3 times .

打印结果
1 2 1
3 3 2
6 4 3
[ 1, 2, 3, 4 ] 10

Example 2

Next, give initvalue an initial value of 0

var arr = [1, 2, 3, 4];
var sum = arr.reduce(function (prev, cur, index, arr) {
  console.log(prev, cur, index);
  return prev + cur;
}, 0);
console.log(arr, sum);

In this example, the index starts from 0, the value of the first prev is the initial value we set to 0, the length of the array is 4, and the reduce function loops 4 times.

打印结果
0 1 0
1 2 1
3 3 2
6 4 3
[ 1, 2, 3, 4 ] 10

Summary: If no initialValue is provided, reduce will execute the callback method starting from index 1, skipping the first index. If initialValue is provided, it starts at index 0.

reduce example algorithm

Compute the cumulative result of an array

var arr = [1, 2, 3, 4];
var sum = arr.reduce(function (prev, cur, index, arr) {
  return prev * cur;
}, 1);
console.log(arr, sum);

打印结果
[ 1, 2, 3, 4 ] 24

Count the number of occurrences of each element in an array

var arr = ["one", "two", "three", "six", "four", "five", "six"];

var newArr = arr.reduce((pre, cur) => {
  console.log(cur, pre);
  if (cur in pre) {
    pre[cur]++;
  } else {
    pre[cur] = 1;
  }
  return pre;
}, {});//这里注意初始值要默认赋予空对象,不然会报错
console.log(newArr);


打印结果
one {}
two { one: 1 }
three { one: 1, two: 1 }
six { one: 1, two: 1, three: 1 }
four { one: 1, two: 1, three: 1, six: 1 }
five { one: 1, two: 1, three: 1, six: 1, four: 1 }
six { one: 1, two: 1, three: 1, six: 1, four: 1, five: 1 }
{ one: 1, two: 1, three: 1, six: 2, four: 1, five: 1 }

Array deduplication

let arr = [1,2,3,4,4,1]
let newArr = arr.reduce((pre,cur)=>{
    if(!pre.includes(cur)){
      return pre.concat(cur)
    }else{
      return pre
    }
},[])
console.log(newArr);

打印结果
[1, 2, 3, 4]

Array flattening from 2D to 1D

let arr = [[0, 1], [2, 3], [4, 5]]
let newArr = arr.reduce((pre,cur)=>{
    return pre.concat(cur)
},[])
console.log(newArr); 

打印结果
[0, 1, 2, 3, 4, 5]

Array flattening from multi-dimensional to one-dimensional

let arr = [[0, 1], [2, 3], [4,[5,6,7]]]
const newArr = function(arr){
   return arr.reduce((pre,cur)=>pre.concat(Array.isArray(cur)?newArr(cur):cur),[])
}
console.log(newArr(arr)); 


打印结果
[0, 1, 2, 3, 4, 5, 6, 7]

sum of object properties

var result = [
    {
        subject: 'math',
        score: 10
    },
    {
        subject: 'chinese',
        score: 20
    },
    {
        subject: 'english',
        score: 30
    }
];
 
var sum = result.reduce(function(prev, cur) {
    return cur.score + prev;
}, 0);
console.log(sum) 

打印结果
60

Guess you like

Origin blog.csdn.net/yjxkq99/article/details/126825703