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

Using react-beautiful-dnd to implement drag and drop between lists

Table of contents Why choose react-beautiful-dnd ...

Detailed explanation of upgrading Python and installing pip under Linux

Linux version upgrade: 1. First, confirm that the...

Detailed explanation of where the images pulled by docker are stored

The commands pulled by docker are stored in the /...

Detailed explanation of gcc command usage under Linux system

Table of contents 1. Preprocessing 2. Compilation...

Detailed explanation of JSON.parse and JSON.stringify usage

Table of contents JSON.parse JSON.parse Syntax re...

Java+Tomcat environment deployment and installation process diagram

Next, I will install Java+Tomcat on Centos7. Ther...

Vue implements start time and end time range query

This article shares with you how to query the sta...

Search optimization knowledge to pay attention to in web design

1. Link layout of the new site homepage 1. The loc...

Mysql stores tree structure through Adjacency List (adjacency list)

The following content introduces the process and ...

Tutorial diagram of installing TomCat in Windows 10

Install TomCat on Windows This article will intro...

A screenshot demo based on canvas in html

Written at the beginning I remember seeing a shar...

A brief discussion on HTML ordered lists, unordered lists and definition lists

Ordered List XML/HTML CodeCopy content to clipboa...

Super simple qps statistics method (recommended)

Statistics of QPS values ​​in the last N seconds ...

Vue implements multi-grid input box on mobile terminal

Recently, the company has put forward a requireme...