Reduce is a powerful method in JavaScript. Some people may not have used it at all in normal development. Learn the usage of reduce and its common scenarios through the following 8 examples.
The reduce method is an array iteration method. Unlike map and filter, the reduce method can cache a variable. During iteration, we can operate this variable and return it.
This is my vernacular explanation. It may not be easy to understand. Let's look at an example
1. Array accumulation
Array accumulation is often encountered in projects, such as calculating the total price of goods. It can be done in one line of code with reduce, and there is no need to define external variables. Reduce is a function without side effects.
// accumulation [1, 2, 3, 4, 5, 6, 7, 8].reduce((a, i) => a + i); // Output: 36 // Cumulative, default to an initial value [1, 2, 3, 4, 5, 6, 7, 8].reduce((a, i) => a + i, 5); // Output: 41 // Tired multiplication [1, 2, 3, 4, 5, 6, 7, 8].reduce((a, i) => a * i); // Output: 40320
2. Find the maximum value of the array
In each iteration of the array, we use Math.max to get the maximum value and return it. Finally, we will get the maximum value of all items in the array.
[1, 2, 3, 4, 5, 6, 7, 8].reduce((a, i) => Math.max(a, i));
Of course, if each item of the array is a number, we can use the... Expansion operator with Math.max.
Math.max(...[1, 2, 3, 4, 5, 6, 7, 8]);
3. Processing irregular arrays
map and reduce are used together to return the spliced results of each sub array.
let data = [ ["gules","128g", "iPhone"], ["north and south","two bedrooms ","128㎡","Foreign house residence"], ["millet","white","Smart Sports Watch","Heart rate blood pressure blood oxygen","Call information reminder"], ["Official sale","2020 Autumn","Basketball","gym shoes","Brand direct mail"] ] let dataConcat = data.map(item=>item.reduce((a,i)=>`${a} ${i}`)) // Output results: ["Red 128 g iPhone" "North south two rooms and one living room 128㎡ Foreign house residence" "Millet white smart sports watch heart rate blood pressure blood oxygen incoming call information reminder" "Official sale of basketball shoes brand direct mail in autumn 2020"]
4. Delete duplicate data items
Check whether the current iteration item exists. If it does not exist, add it to the array.
let array = [1, 2, 3, 'a', 'b', 'c', 1, 2, 3, 'a', 'b', 'c']; array.reduce((noDupes, curVal) => { if (noDupes.indexOf(curVal) === -1) { noDupes.push(curVal) } return noDupes }, []) // Output: [1, 2, 3, 'a', 'b', 'c']
5. Verify whether the brackets are legal
This is a very clever usage, which I saw on dev.to. If the result is equal to 0, the number of parentheses is legal.
[..."(())()(()())"].reduce((a,i)=> i === '(' ? a+1 : a-1 , 0); // Output: 0 // Use cycle mode let status=0 for (let i of [..."(())()(()())"]) { if(i === "(") status = status + 1 else if(i === ")") status = status - 1 if (status < 0) { break; } }
6. Group by attribute
Group the data according to the specified key. Here, I use the country field to group. During each iteration, check whether the current country exists. If it does not exist, create an array and insert the data into the array. And returns an array.
let obj = [ {name: 'Zhang San', job: 'Data Analyst', country: 'China'}, {name: 'ACE', job: 'scientist', country: 'China'}, {name: 'Rael', job: 'scientist', country: 'U.S.A'}, {name: 'Bob', job: 'software engineer', country: 'India'}, ] obj.reduce((group, curP) => { let newkey = curP['country'] if(!group[newkey]){ group[newkey]=[] } group[newkey].push(curP) return group }, []) // Output: [ China: [{...}, {...}] India: [{...}] U.S.A: [{...}] ]
7. Array flattening
The array shown here has only one level of depth. If the array is multi-level, recursion can be used for processing
[[3, 4, 5], [2, 5, 3], [4, 5, 6]].reduce((singleArr, nextArray) => singleArr.concat(nextArray), []) // Output: [3, 4, 5, 2, 5, 3, 4, 5, 6]
Of course, you can also use the. flat method of ES6 instead
[ [3, 4, 5], [2, 5, 3], [4, 5, 6] ].flat();
8. Reverse string
This is also a wonderful implementation method
[..."hello world"].reduce((a,v) => v+a)
perhaps
[..."hello world"].reverse().join('')
last
Through the above understanding, you can see the powerful usage of reduce. Use reduce to simplify code and abstract code.
If you have better examples, please add them in the comment area.