8 JS reduce usage examples and reduce operation methods

8 JS reduce usage examples and reduce operation methods

reduce method is an array iteration method. Unlike map and filter , reduce method can cache a variable. During iteration, we can operate on this variable and then return it.

This is my explanation in plain language. It may still be difficult to understand. Let’s look at the examples below.

1. Array Accumulation

Array accumulation is often encountered in projects, such as calculating the total price of goods. Using reduce , it can be done in one line of code without defining external variables. Reduce is a function with no side effects.

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

// Accumulate, with a default initial value of [1, 2, 3, 4, 5, 6, 7, 8].reduce((a, i) => a + i, 5);
// Output: 41

// Accumulate [1, 2, 3, 4, 5, 6, 7, 8].reduce((a, i) => a * i);
// Output: 40320

2. Find the maximum value of an array

In each iteration of the array, we use Math.max to get the maximum value and return it. In the end, 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 in the array is a number, we can use the ... spread operator in conjunction with Math.max .

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

3. Dealing with irregular arrays

By using map and reduce together, the concatenated result of each sub-array is returned.

let data = [
  ["red","128g","iPhone"],
  ["North-South","Two bedrooms and one living room","128㎡","Western-style house"],
  ["Xiaomi","white","smart sports watch","heart rate, blood pressure, blood oxygen","call message reminder"], 
  ["Official Release","Autumn 2020","Basketball","Sneakers","Brand Direct Mail"]
]
let dataConcat = data.map(item=>item.reduce((a,i)=>`${a} ${i}`))

// Output:
["Red 128g Apple mobile phone"
"North-South two-bedroom and one-living room 128㎡ Western-style house"
"Xiaomi white smart sports watch heart rate, blood pressure, blood oxygen, call information reminder"
"Official sale of 2020 autumn basketball shoes brand direct mail"]

4. Remove data duplication

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

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 the brackets are legal

This is a very clever usage, which I saw on dev.to. If the result is equal to 0, it means that the number of brackets is legal.

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

// Using loop method 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 attributes

Group the data by the specified key. Here I use the country field to group. During each iteration, check whether the current country exists. If not, create an array and insert the data into the array. And returns the array.

let obj = [
  {name: '张三', job: 'Data Analyst', country: '中国'},
  {name: 'Ace', job: 'Scientist', country: 'China'},
  {name: 'Leir', job: 'Scientist', 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: [{…}]
  USA: [{…}] ]

7. Array Flattening

The array shown here is only one level deep. If the array is multi-level, 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]

Of course, you can also use ES6's .flat method instead

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

8. Reverse a String

This is also a very wonderful way to achieve

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

or

[..."hello world"].reverse().join('')

You may also be interested in:
  • 5 Basic Usage Examples of reduce() in JavaScript
  • JavaScript Array reduce() Method
  • Summary of using the reduce() method in JS
  • js uses the reduce method to make your code more elegant
  • Detailed explanation of JavaScript Reduce
  • Detailed explanation of the basic usage of JavaScript reduce

<<:  Detailed tutorial on installing MySQL database on Alibaba Cloud Server

>>:  How to deploy zabbix_agent in docker

Recommend

Detailed explanation of webpage screenshot function in Vue

Recently, there is a requirement for uploading pi...

Six-step example code for JDBC connection (connecting to MySQL)

Six steps of JDBC: 1. Register the driver 2. Get ...

Zabbix monitors mysql instance method

1. Monitoring planning Before creating a monitori...

mysql8.0.23 msi installation super detailed tutorial

1. Download and install MySql Download MySql data...

Detailed steps for installing and configuring mysql 5.6.21

1. Overview MySQL version: 5.6.21 Download addres...

Use h1, h2, and h3 tags appropriately

In the process of making web pages, it is inevita...

SQL fuzzy query report: ORA-00909: invalid number of parameters solution

When using Oracle database for fuzzy query, The c...

Solve the problem of spring boot + jar packaging deployment tomcat 404 error

1. Spring boot does not support jsp jar package, ...

Detailed explanation of MySQL table name case-insensitive configuration method

By default, MySQL in Linux distinguishes between ...

How to implement encryption and decryption of sensitive data in MySQL database

Table of contents 1. Preparation 2. MySQL encrypt...

A Brief Analysis of CSS Selector Grouping

Selector Grouping Suppose you want both the h2 el...

MySQL data operation-use of DML statements

illustrate DML (Data Manipulation Language) refer...

VUE + OPENLAYERS achieves real-time positioning function

Table of contents Preface 1. Define label style 2...

Detailed explanation of JavaScript's garbage collection mechanism

Table of contents Why do we need garbage collecti...

Detailed explanation of MySQL user and permission management

This article uses examples to describe the manage...