Detailed explanation of Js_reduce usage (super detailed!!!)

16455337:

1. reduce syntax

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

  1. The recude function receives two parameters, one is the callback function and the other is the initial assignment
  2. 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)
  3. The second parameter is the initial value passed to the function, not required

2. Example Analysis

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);

print result
1 2 1
3 3 2
6 4 3
[ 1, 2, 3, 4 ] 10

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

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);

Print result
0 1 0
1 2 1
3 3 2
6 4 3
[ 1, 2, 3, 4 ] 10

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.

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.

3. In-depth understanding combined with examples

(1) Calculate the cumulative result of the array

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

print result
[1, 2, 3, 4] 24

(2) Count the number of occurrences of each element in the 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 }

(3) 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);

print result
[1, 2, 3, 4]

(4) Array flattening from two-dimensional to one-dimensional

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

print result
[0, 1, 2, 3, 4, 5]

(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)); 

Print result
[0, 1, 2, 3, 4, 5, 6, 7]

(6) Summing of object attributes

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) 

print result
60

Guess you like

Origin blog.csdn.net/qq_41916378/article/details/126053911