reduce
The method is an iterative method of an array, andmap
、filter
different,reduce
The method can cache a variable, and we can operate this variable during iteration and then return it.
This is my plain explanation, and it may not be easy to understand. Let's take a look at the example below
1. Array accumulation
Array accumulation is often encountered by projects, such as calculating the total price of the product, etc.reduce
It can be done in one line of code, and there is no need to define external variables. Reduce is a function with no side effects at all.
// Accumulated[1, 2, 3, 4, 5, 6, 7, 8].reduce((a, i) => a + i); // Output: 36 // Accumulate, default to an initial value[1, 2, 3, 4, 5, 6, 7, 8].reduce((a, i) => a + i, 5); // Output: 41 // tiring[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 useGet the maximum value and return, and finally we will get the maximum value of all items in the array.
[1, 2, 3, 4, 5, 6, 7, 8].reduce((a, i) => (a, i));
Of course if each item in the array is a number we can use...expand operator andCooperate.
(...[1, 2, 3, 4, 5, 6, 7, 8]);
3. Handle irregular arrays
passmap
andreduce
Use together to return the result of splicing of each subarray.
let data = [ ["red","128g", "Apple phone"], ["North and South","Two bedrooms and one living room","128㎡","Battlehouse"], ["Millet","White","Smart Sports Watch","Heart rate, blood pressure, blood oxygen","Call message reminder"], ["Officially available","Autumn 2020","basketball","sneakers","Brand Direct Mail"] ] let dataConcat = (item=>((a,i)=>`${a} ${i}`)) // Output result:["Red 128g Apple phone" "North and South, Two bedrooms and One Living Room, 128㎡ Bungalow Residence" "Xiaomi White Smart Sports Watch Heart Rate Blood Pressure Blood Oxygen Call Information Reminder" "Officially released 2020 autumn basketball sneakers brand direct mail"]
4. Delete duplicates of data
Check if the current iteration item exists, if not added to the array.
let array = [1, 2, 3, 'a', 'b', 'c', 1, 2, 3, 'a', 'b', 'c']; ((noDupes, curVal) => { if ((curVal) === -1) { (curVal) } return noDupes }, []) // Output: [1, 2, 3, 'a', 'b', 'c']
5. Verify whether the brackets are legal
This is a very clever usage, the usage I saw above. If the result is equal to 0, the number of brackets is legal.
[..."(())()(()())"].reduce((a,i)=> i === '(' ? a+1 : a-1 , 0); // Output: 0 // Use looplet 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 by the specified key. Here I use the country field to group it, check whether the current country exists during each iteration, and create an array if it does not exist, insert the data into the array. and return the array.
let obj = [ {name: 'Zhang San', job: 'Data Analyst', country: 'China'}, {name: 'Ace', job: 'the scientist', country: 'China'}, {name: 'Rel', job: 'the scientist', country: 'USA'}, {name: 'Bob', job: 'Software Engineer', country: 'India'}, ] ((group, curP) => { let newkey = curP['country'] if(!group[newkey]){ group[newkey]=[] } group[newkey].push(curP) return group }, []) // Output:[ China: [{…}, {…}] India: [{…}] USA: [{…}] ]
7. Array flattening
The array shown here has only one level of depth. If the array is multi-level, it can be processed using recursion.
[[3, 4, 5], [2, 5, 3], [4, 5, 6]].reduce((singleArr, nextArray) => (nextArray), []) // Output: [3, 4, 5, 2, 5, 3, 4, 5, 6]
Of course, ES6's .flat method can also be used instead
[ [3, 4, 5], [2, 5, 3], [4, 5, 6] ].flat();
8. Invert the string
This is also a very wonderful way to implement it
[..."hello world"].reduce((a,v) => v+a)
or
[..."hello world"].reverse().join('')