js uses the reduce method to make your code more elegant
- 2021-11-13 06:23:52
- OfStack
Preface
In the actual project, the most common probably is in the calculation, loop logic processing, can use the array of reduce method can also solve many problems, make your code style more elegant!
reduce syntax
arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])
Parameter description
The reducer function needs to receive four parameters, which are
callback
Accumulator The accumulator accumulates the return value of the callback; It is the cumulative value returned on the last callback call, or initialValue. Current Value The element being processed in the array. Current Index This is an optional parameter, the index of the current element being processed in the array. If initialValue is provided, the starting index number is 0, otherwise it starts from index 1. Source Array This is an optional argument that calls the array of reduce ()initialValue
As the value of the first parameter when the callback function is called for the first time. If no initial value is provided, the first element in the array is used. Calling reduce on an empty array with no initial value will report an error.Return value
The result of the cumulative processing of the function1 Some common methods of reduce
The sum of all the elements in the array
const arr = [1, 2, 3, 4];
const result = arr.reduce((acc, cur) => acc + cur)
console.log(result) // 10
Count the number of occurrences of each element in the array
const nums = ['1', '1', '1', '2', '3'];
const countednums = nums.reduce((acc, cur) => {
if (cur in acc) {
acc[cur]++;
}
else {
acc[cur] = 1;
}
return acc;
}, {});
console.log(countednums); // {1: 3, 2: 1, 3: 1}
Flattened array
const arr = [['a', 'b'], ['b', 'c'], ['d', 'e']]
const flatten = arr => {
return arr.reduce((acc, cur) => {
return acc.concat(cur)
}, [])
}
console.log(flatten(arr)); // ["a", "b", "b", "c", "d", "e"]
Array de-duplication
const arr = [22,341,124,54,4,21,4,4,1,4,4];
const result = arr.sort().reduce((acc, cur) => {
if(acc.length === 0 || acc[acc.length-1] !== cur) {
acc.push(cur);
}
return acc;
}, []);
console.log(result); // [1, 124, 21, 22, 341, 4, 54]
Find the maximum value in the array
const arr = [1, 2, 3, 5, 1]
let result = arr.reduce((acc, cur) => Math.max(acc, cur))
console.log(result)
Call promise in sequence
In this way, value of promise is actually processed, and value of the previous promise is treated as value of the next promise.
const prom1 = a => {
return new Promise((resolve => {
resolve(a)
}))
}
const prom2 = a => {
return new Promise((resolve => {
resolve(a * 2)
}))
}
const prom3 = a => {
return new Promise((resolve => {
resolve(a * 3)
}))
}
const arr = [prom1, prom2, prom3]
const result = arr.reduce((all, current) => {
return all.then(current)
}, Promise.resolve(10))
result.then(res => {
console.log(res);
})
Finally
This article shares some common reduce processing methods in daily development, which can be used directly in your project or packaged twice.