Reduce method is a powerful method in JavaScript. Some people may not use it at all in normal development. Through the following 8 examples, learn how to use Reduce and its common scenarios.

The Reduce method is an array iteration method. Unlike Map and filter, reduce method can cache a variable. During iteration, we can manipulate the variable and return it.

This is my explanation in plain English, maybe it’s not easy to understand, but let’s look at an example

1. Array accumulation

Array accumulation is often encountered in projects, such as calculating the total price of goods. Reduce can be done in one line of code without defining external variables. Reduce is a completely side-effect free function.

/ / accumulation
[1.2.3.4.5.6.7.8].reduce((a, i) = > a + i);
// Output: 36

// add, default an initial value
[1.2.3.4.5.6.7.8].reduce((a, i) = > a + i, 5);
// Output: 41

/ / multiplicative
[1.2.3.4.5.6.7.8].reduce((a, i) = > a * i);
// Output: 40320
Copy the code

2. Find the maximum value of the array

At each iteration of the array, we use math.max to get the maximum value and return it, and finally we get the maximum value for all the items in the array.

[1.2.3.4.5.6.7.8].reduce((a, i) = > Math.max(a, i));
Copy the code

Of course, if each item in the array is a number, we can use… The expansion operator works with math.max.

Math.max(... [1, 2, 3, 4, 5, 6, 7, 8]);Copy the code

3. Handle irregular arrays

Map and Reduce are used together to return the concatenated result of each subarray.

let data = [
  ["Red"."128g".The iPhone.],
  ["Civil"."Two bedrooms and one living room."."128 ㎡"."Mansion house"],
  ["Millet"."White"."Smart Sports Watch"."Heart rate blood pressure blood oxygen."."Call message Alert"], 
  ["Official sale"."Fall 2020"."Basketball"."Sneakers"."Brand Direct Mail"]]let dataConcat = data.map(item= >item.reduce((a,i) = >`${a} ${i}`))

// Output result:
["Red 128GB iPhone"
"North and South two rooms one room 128 square meters house"
"Xiaomi White smart sports watch Heart rate blood pressure oxygen call information reminder"
"Official release of fall 2020 Basketball shoe brand direct mail"]
Copy the code

4. Delete data duplicates

Checks if the current iteration item exists and adds it to the array if not.

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']
Copy the code

5. Verify that the parentheses are valid

This is a clever usage, one I saw in dev.to. If the result is equal to 0, the number of parentheses is valid.

[..."() () () () () ()"].reduce((a,i) = > i === '(' ? a+1 : a-1 , 0);
// Output: 0

// Use a loop
let status=0
for (let i of [..."() () () () () ()"]) {
  if(i === "(")
    status = status + 1
  else if(i === ")")
    status = status - 1
  if (status < 0) {
    break; }}Copy the code

6. Group by attribute

Group the data according to the specified key. Here, I use the country field to group the data. During each iteration, check whether the current country exists. And returns an array.

let obj = [
  {name: 'Joe'.job: 'Data analyst'.country: 'China'},
  {name: 'ace'.job: 'Scientist'.country: 'China'},
  {name: 'real'.job: 'Scientist'.country: 'the United States'},
  {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: [{...}] United States: [{...}]]Copy the code

7. Array flattening

The array shown here has only one level of depth. If the array is multilevel, you can use recursion to process it

[[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]
Copy the code

Of course, you can use the.flat method of ES6 instead

[[3.4.5], 
	[2.5.3], 
	[4.5.6]
].flat();
Copy the code

8. Reverse the string

This is also a fantastic way to do it

[..."hello world"].reduce((a,v) = > v+a)
Copy the code

or

[..."hello world"].reverse().join(' ')
Copy the code

The last

From the above, you can see the powerful use of Reduce. Simplify code better by using Reduce, abstracting code.

If you have any better examples, feel free to add them in the comments section.