preface
Many front-end developers know that the reduce method of arrays can be used to sum arrays, but many people don’t know when you ask what the parameters in an array represent. So very few people use this method at work. Now I will give you a detailed explanation through this article, and expand to you through several cases
The reduce method
Here’s how the API is used and what each parameter means:
arr.reduce((prev,cur,index,arr) = >{
},init)
Copy the code
- Arr: will be the original array
- Prev: represents the return value when the callback was last called, or the initial value init
- Cur: Represents the array element currently being processed
- Index: Indicates the index of the array element being processed, 0 if init is provided, 1 otherwise
- Init: indicates the initial value
case
Array sum
const arr = [1.2.3.4.5.6.7]
const sum = arr.reduce((pre,cur) = >{
return pre +cur
})
console.log(sum)
Copy the code
The array summation method is the most common use case for this reduce method, but many people just know to return pre + cur to return the sum, if I slightly change the method like this
const arr = [1.2.3.4.5.6.7]
const sum = arr.reduce((pre,cur) = >{
return pre +cur
},2)
console.log(sum)
Copy the code
Do you think the result is the same? The answer is clearly no, and I’ll explain it to you:
- So the first thing we want to make clear is that pre is the return value of the last callback, or the initial value init.
- So when we first call it, the first case is we didn’t set init, so without init, index is going to be 1, and actually the first time we implicitly called pre+cur, you can kind of think of it behind the scenes pre is 0+cur:1. So what we see on the console is that the whole calculation is index 1 minus 6.
- In the second case, init is set to 2, so the initial value for pre is 2, so the first time, index starts at 0, the first call returns
2+arr[1]
=3, the whole process index is executed from 0 to 6, a total of 7 times
Count the number of occurrences of each element in the array
let person = ['李白'.'Athena'.'Angela'.'李白'.'Zhuge Liang'.'Angela']
let nameObj = person.reduce((pre,cur) = >{
if( cur in pre){
pre[cur]++
}
else{
pre[cur] = 1
}
return pre
}, {})
console.log(nameObj) {Li Bai: 2, Athena: 1, Angela: 2, Zhuge Liang: 1}
Copy the code
Array flattening
const arr2 = [1[2[3[4.5]]].6]
const newArr = (arr) = > {
return arr.reduce((pre,cur) = >{
return pre.concat(Array.isArray(cur) ? newArr(cur) : cur)
},[])
}
console.log(newArr(arr2)) // [1, 2, 3, 4, 5, 6]
Copy the code
This method is achieved by combining recursive methods with reduce. Of course, there is more than one way to flatten arrays, but there are other ways to flatten arrays. Check out another of my blog posts on how to flatten arrays
Array to heavy
const arr3 = [1.2.3.4.5.3.2.1.6.4.7.8]
const resultArr = arr3.reduce((pre,cur) = >{
if(! pre.includes(cur)){return pre.concat(cur)
}
else{
return pre
}
},[])
console.log(resultArr)
Copy the code