preface
Previously, we only knew that reduce could be used for array summation
But reduce does much more than that, so here’s a summary
usage
Array. reduce(function(Accumulator, currentValue, currentIndex, Array), initialValue);
-
Accumulator: Is the return value of the last call to the function.
The first time for the initialValue | | arr [0]
-
CurrentValue: The value that the function in the array is processing.
The first time the initialValue | | arr [1]
-
CurrentIndex: (Optional) Index of the element being processed in the data
If initialValue is provided start at 0 otherwise start at 1
-
Array: (Optional) Array to invoke Reduce
-
InitialValue: (optional) initialValue of the accumulator. The first value of the accumulator is currentValue
Note: An error is reported when the reduce method is called on an empty array with no initial value set.
Let’s look at an example just to get a sense of it
// There is an initial value; [1.2.3.4].reduce(function (accumulator, currentValue, currentIndex, array) {
return accumulator + currentValue
}, 10) / / 20
Copy the code
callback | accumulator | currentValue | currentIndex | array | return value |
---|---|---|---|---|---|
first call | 10(initial value) | 1(first element of array) | 0(with an initial value of 0) | [1, 2, 3, 4] | 11 |
second call | 11 | 2 | 1 | [1, 2, 3, 4] | 13 |
third call | 13 | 3 | 2 | [1, 2, 3, 4] | 16 |
fourth call | 16 | 4 | 3 | [1, 2, 3, 4] | 20 |
Usage scenarios
case1
You can do a simple array sum
[1.2.3.4].reduce((a, b) = > a + b) / / 10
Copy the code
case2
You can flatten a two-dimensional array
[[1.2],
[3.4],
[5.6],
].reduce((a, b) = > a.concat(b), []) // [1, 2, 3, 4, 5, 6]
Copy the code
case3
You can count the number of occurrences of each element in the array
Set the initial value to {} as the container in which we put the result and then initialize the key if the container has the element and does not have it
[1.2.3.1.2.3.4].reduce((items, item) = > {
if (item in items) {
items[item]++
} else {
items[item] = 1
}
return items
}, {}) // {1: 2, 2: 2, 3: 2, 4: 1}
Copy the code
case4
Array to heavy
/ / method
[
1.2.3.1.2.3.4.4.5
].reduce((init, current) = > {
// The first time init is empty push the first element into init
// Then each subsequent current looks in init to see if the same element already exists
// Keep pushing if you don't find it
if (init.length === 0 || init.indexOf(current) === -1) {
init.push(current)
}
return init
}, []) //[1, 2, 3, 4, 5]
Copy the code
/ / method 2
[1.2.3.1.2.3.4.4.5].sort().reduce((init, current) = > {
// Sort the array first
// Push the first element into init
// Determine if each subsequent element is the same as the last element in init
// Continue pushing if different
if (init.length === 0 || init[init.length - 1] !== current) {
init.push(current)
}
return init
}, []) //[1, 2, 3, 4, 5]
Copy the code