The reduce() method is explained in detail

Definition and Usage
The reduce() method reduces an array to a single value.
The reduce() method executes the provided function for each value of the array (from left to right).
The return value of the function is stored in the accumulator (result/total).

Note: The reduce() method is not executed for array elements that have no value.
Note: The reduce() method does not mutate the original array.

grammar

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

parameter value

parameter describe
function(total, currentValue, index, arr) required. Function to run for each element in the array.

Function parameters:

parameter describe
total required. initialValue, or the value previously returned by the function.
currentValue required. The value of the current element.
index optional. The array index of the current element.
arr optional. the array object to which the current element belongs
initialValue optional. The value passed to the function as the initial value.

1. Example analysis initialValue parameter

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


VM6252:3 1 2 1
VM6252:3 3 3 2
VM6252:3 6 4 3
VM6252:6 (4) [1, 2, 3, 4] 10

It can be seen here that 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, but the reduce function loops 3 times.

look at one more

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


VM282:3 0 1 0
VM282:3 1 2 1
VM282:3 3 3 2
VM282:3 6 4 3
VM282:6 (4) [1, 2, 3, 4] 10

Conclusion: 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.

2. Simple usage of reduce

var  arr = [1, 2, 3, 4];
var sum = arr.reduce((x,y)=>x+y)
var mul = arr.reduce((x,y)=>x*y)
console.log( sum ); //求和,10
console.log( mul ); //求乘积,24

3. Advanced usage of reduce

(1) Calculate the number of occurrences of each element in the array

let names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];

let nameNum = names.reduce((pre,cur)=>{
    
    
  if(cur in pre){
    
    
    pre[cur]++
  }else{
    
    
    pre[cur] = 1 
  }
  return pre
},{
    
    })
console.log(nameNum); //{Alice: 2, Bob: 1, Tiff: 1, Bruce: 1}

(2) 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]

(3) Convert a two-dimensional array to one-dimensional

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]

(4) Convert multidimensional arrays 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]

(5) Summing the attributes in the object

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/wangxinxin1992816/article/details/124536863