reduce() Things that can be done with methods ,for loop , perhaps forEach Methods can be done sometimes , Then why use it reduce()? This problem , I thought about it before , There's really no reason for that , The only thing you can find is : There are many ways to success , But there's always a way to get there , Or maybe reduce() Push the grid higher ...
1. grammar
arr.reduce(callback,[initialValue])
reduce Execute the callback function for each element in the array in turn , Does not include elements in the array that have been deleted or have never been assigned , Accept four parameters : Initial value ( Or the return value of the last callback function ), Current element value , Current index , call reduce Array of .
callback ( Functions that execute each value in the array , There are four parameters )
1、previousValue ( The value returned by the last call callback , Or the initial value provided (initialValue))
2、currentValue ( Elements currently being processed in the array )
3、index ( The index of the current element in the array )
4、array ( call reduce Array of )
initialValue ( As the first call callback The first parameter of .
2. Instance analysis initialValue Parameters
Let's start with the first example
const arr = [1, 2, 3, 4];
const sum = arr.reduce((prev, cur, index, arr) => {
console.log(prev, cur, index);
return prev + cur;
})
console.log(arr, sum);
Print the results :
1 2 1
3 3 2
6 4 3
[1, 2, 3, 4] 10
You can see here , The above example index It's from 1 At the beginning , For the first time prev The value of is the first value of the array . The length of the array is 4, however reduce Function cycle 3 Time .
Let's look at the second example :
const arr = [1, 2, 3, 4];
const sum = arr.reduce((prev, cur, index, arr) => {
console.log(prev, cur, index);
return prev + cur;
},0) // Notice that the initial value is set here
console.log(arr, sum);
Print the results :
0 1 0
1 2 1
3 3 2
6 4 3
[1, 2, 3, 4] 10
This example index It's from 0 At the beginning , For the first time prev The value of is the initial value we set 0, The length of the array is 4,reduce Function cycle 4 Time .
Conclusion : If not provided initialValue,reduce From the index 1 Where we started callback Method , Skip the first index . Provided initialValue, From the index 0 Start .
Be careful : If the array is empty , Application reduce What's the situation ?
var arr = [];
var sum = arr.reduce(function(prev, cur, index, arr) {
console.log(prev, cur, index);
return prev + cur;
})
// Report errors ,"TypeError: Reduce of empty array with no initial value"
But if we set the initial value, we will not report an error , as follows
var arr = [];
var sum = arr.reduce(function(prev, cur, index, arr) {
console.log(prev, cur, index);
return prev + cur;
},0)
console.log(arr, sum); // [] 0
So it's generally safer for us to provide initial values
3.reduce Simple usage
Of course, the simplest is our usual array summation , We've got the product .
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 ); // Sum up ,10
console.log( mul ); // Find the product ,24
4.reduce Advanced usage of
- Count the number of occurrences of each element in the array
let names = ['A', 'D', 'T', 'B', 'A'];
let nameNum = names.reduce((pre,cur)=>{
if(cur in pre){
pre[cur]++
}else{
pre[cur] = 1
}
return pre
},{})
console.log(nameNum); //{A: 2, B: 1, T: 1, D: 1}
- Array weight removal
let arr = [1,2,2,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, 4]
- Convert a two-dimensional array to a one-dimensional array
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]
- The sum of attributes in an object
var result = [
{
subject: ' Chinese language and literature ',
score: 90
},
{
subject: ' mathematics ',
score: 90
},
{
subject: ' English ',
score: 100
}
];
var sum = result.reduce(function(prev, cur) {
return cur.score + prev;
}, 0);
console.log(sum) //280