js uses the reduce method to make your code more elegant

js uses the reduce method to make your code more elegant

Preface

In actual projects, the most common processing may be in calculation and loop logic. You can use the reduce method in the array to solve many problems and make your code style more elegant!

reduce syntax

arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])

Parameter Description

The reducer function needs to receive 4 parameters:

callback

  • Accumulator
    • The accumulator accumulates the return value of the callback; it is the accumulated value returned by the last call to the callback, or the initialValue.
  • Current Value
    • The element in the array being processed.
  • Current Index
    • This is an optional parameter, the index of the current element in the array being processed. If initialValue is provided, the starting index is 0, otherwise it starts at index 1.
  • Source Array
    • This is an optional parameter, the array to call reduce() on.

initialValue

  • The value to be used as the first argument when the callback function is first called. If no initial value is provided, the first element in the array will be used. Calling reduce on an empty array with no initial value will result in an error.

Return Value

  • The result of the function accumulation processing

Some common reduce methods

The sum of all elements in the array

const arr = [1, 2, 3, 4];
const result = arr.reduce((acc, cur) => acc + cur)
​
console.log(result) // 10

Count the number of times each element occurs in an array

const nums = ['1', '1', '1', '2', '3'];
const countednums = nums.reduce((acc, cur) => { 
  if (cur in acc) {
    acc[cur]++;
  }
  else {
    acc[cur] = 1;
  }
  return acc;
}, {});
​
console.log(countednums); // {1: 3, 2: 1, 3: 1}

Flattening an array

const arr = [['a', 'b'], ['b', 'c'], ['d', 'e']]
const flatten = arr => {
  return arr.reduce((acc, cur) => {
    return acc.concat(cur)
  }, [])
}
​
console.log(flatten(arr)); // ["a", "b", "b", "c", "d", "e"]

Array deduplication

const arr = [22,341,124,54,4,21,4,4,1,4,4];
const result = arr.sort().reduce((acc, cur) => {
    if(acc.length === 0 || acc[acc.length-1] !== cur) {
        acc.push(cur);
   }
    return acc;
}, []);
​
console.log(result); // [1, 124, 21, 22, 341, 4, 54]

Find the maximum value in an array

const arr = [1, 2, 3, 5, 1]
let result = arr.reduce((acc, cur) => Math.max(acc, cur))
​
console.log(result)

Promises are called in order

This method actually processes the value of the promise, and processes the value of the previous promise as the value of the next promise.

const prom1 = a => {
  return new Promise((resolve => {
    resolve(a)
  }))
}
const prom2 = a => {
  return new Promise((resolve => {
    resolve(a * 2)
  }))
}
const prom3 = a => {
  return new Promise((resolve => {
    resolve(a * 3)
  }))
}

const arr = [prom1, prom2, prom3]
const result = arr.reduce((all, current) => {
  return all.then(current)
}, Promise.resolve(10))

result.then(res => {
  console.log(res);
})

at last

This article shares some reduce processing methods that are commonly used in daily development. You can use them directly in your project or repackage them.

This is the end of this article about how to use the reduce method in js to make your code more elegant. For more relevant content about the js reduce method to make the code elegant, please search for previous articles on 123WORDPRESS.COM or continue to browse the related articles below. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • 5 Basic Usage Examples of reduce() in JavaScript
  • JavaScript Array reduce() Method
  • 8 JS reduce usage examples and reduce operation methods
  • Summary of using the reduce() method in JS
  • Detailed explanation of JavaScript Reduce
  • Detailed explanation of the basic usage of JavaScript reduce

<<:  Installation and configuration method of Zabbix Agent on Linux platform

>>:  Detailed explanation of MySQL Strict Mode knowledge points

Recommend

Understanding and using React useEffect

Table of contents Avoid repetitive rendering loop...

Build Maven projects faster in Docker

Table of contents I. Overview 2. Conventional mul...

win2008 server security settings deployment document (recommended)

I had been working on the project before the New ...

How to set password for mysql version 5.6 on mac

MySQL can be set when it is installed, but it see...

Docker adds a bridge and sets the IP address range

I don't know if it's because the binary d...

How to install and configure ftp server in CentOS8.0

After the release of CentOS8.0-1905, we tried to ...

Detailed explanation of using top command to analyze Linux system performance

Introduction to Linux top command The top command...

Talk about important subdirectory issues in Linux system

/etc/fstab Automatically mount partitions/disks, ...

Getting Started Tutorial on Using TS (TypeScript) in Vue Project

Table of contents 1. Introducing Typescript 2. Co...

JavaScript two pictures to understand the prototype chain

Table of contents 1. Prototype Relationship 2. Pr...

A brief discussion on the corresponding versions of node node-sass sass-loader

Table of contents The node version does not corre...

Nginx server https configuration method example

Linux: Linux version 3.10.0-123.9.3.el7.x86_64 Ng...

Detailed explanation of the use of redux in native WeChat applet development

premise In complex scenarios, a lot of data needs...

Examples of 4 methods for inserting large amounts of data in MySQL

Preface This article mainly introduces 4 methods ...