reduce usage instances and reduce operation modes of 8 JS

  • 2021-11-23 22:14:14
  • OfStack

reduce Method is an iterative method of an array, and map , filter Different, reduce Method can cache 1 variable, which we can manipulate and return when iterating.

This is my vernacular explanation, which may not be easy to understand. Let's look at the example below

1. Array accumulation

Array accumulation is often encountered in projects, such as calculating the total price of goods, etc., using reduce You can do it with 1 line of code, and you don't need to define external variables. reduce is a function without side effects at all.


//  Accumulation 
[1, 2, 3, 4, 5, 6, 7, 8].reduce((a, i) => a + i);
//  Output: 36

//  Accumulation, default 1 Initial values 
[1, 2, 3, 4, 5, 6, 7, 8].reduce((a, i) => a + i, 5);
//  Output: 41

//  Cumulative 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 the Math.max 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 every item in the array is a number, we can use the... expansion operator and Math.max Cooperate.


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

3. Working with irregular arrays

Pass map And reduce Use together to return the spliced results of each subarray.


let data = [
  [" Red ","128g", " Apple phone "],
  [" North and South "," Two chambers 1 Hall ","128 ㎡ "," Villa residence "],
  [" Millet "," White "," Smart sports watch "," Heart rate, blood pressure and blood oxygen "," Call message reminder "], 
  [" Official sale ","2020 Autumn of "," Basketball "," Sneakers "," Brand direct mail "]
]
let dataConcat = data.map(item=>item.reduce((a,i)=>`${a} ${i}`))

//  Output: 
[" Red  128g  Apple phone "
" North and South   Two chambers 1 Hall  128 ㎡   Villa residence "
" Millet   White   Smart sports watch   Heart rate, blood pressure and blood oxygen   Call message reminder "
" Official sale  2020 Autumn of   Basketball   Sneakers   Brand direct mail "]

4. Delete duplicates

Check whether the current iteration item exists, and 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 that parentheses 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 loop mode 
let status=0
for (let i of [..."(())()(()())"]) {
  if(i === "(")
    status = status + 1
  else if(i === ")")
    status = status - 1
  if (status < 0) {
    break;
  }
}

6. Grouping by Attribute

The data is grouped according to the specified key, where I use the country field to group, check whether the current country exists during each iteration, and if it does not exist, create an array and insert the data into the array. And returns an array.


let obj = [
  {name: ' Zhang 3', job: ' Data analyst ', country: ' China '},
  {name: ' Ace ', job: ' Scientists ', country: ' China '},
  {name: ' Rayle ', job: ' Scientists ', country: ' 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 : [{ … }] ]

7. Array flattening

The array shown here is only 1 level deep. If the array is multi-level, recursion can be used 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]

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


[ [3, 4, 5], 
 [2, 5, 3], 
 [4, 5, 6]
].flat();

8. Invert the string

This is also a wonderful way to achieve it


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

Or


[1, 2, 3, 4, 5, 6, 7, 8].reduce((a, i) => Math.max(a, i));

0


Related articles: