Basic usage of reduce function
Grammar:
arr.reduce(callback,[initialValue])
Copy the code
What it does: Receives a function as an accumulator that executes callbacks for each element in an array, excluding elements that were deleted or never assigned, and takes four arguments: the initial value (the value returned by the last callback), the current element value, the current index, and the original array
Simple example: Add all the values in an array
// Define a set of numbers
let nums = [10.20.30.40.50];
let total = nums.reduce(function(preValue, n) {
//return The sum of the two values
return preValue + n
//preValue Sets the initial value to 0
}, 0)
// Prints 150
console.log(total)
Copy the code
Note: preValue is the last return value:
The number of | The return value | An array of numerical |
---|---|---|
For the first time, | PreValue = 0 (initial value) | N = 10, |
The second time | PreValue = 0 (last preValue value) + 10= 10 | N = 20. |
The third time | preValue = 10 + 20 = 30 | N = 30, |
For the fourth time | preValue = 30 + 30 = 60 | N = 40, |
The fifth time | preValue = 60 + 40 =100 | n = 50 |
The final result | preValue = 100 + 50 = 150 |