Summary of using the reduce() method in JS

Summary of using the reduce() method in JS

For a long time, I found it difficult to understand the specific usage of the reduce() method, and I rarely used it. In fact, if you can really understand it, we can use it in many places, so today we will briefly talk about the usage of reduce() in JS.

1. Grammar

arr.reduce(function(prev,cur,index,arr){
...
}, init);

in,
arr represents the original array;
prev represents the return value of the last callback call, or the initial value init;
cur represents the array element currently being processed;
index represents the index of the array element currently being processed. If the init value is provided, the index is 0, otherwise the index is 1;
init indicates the initial value.

Does it look complicated? It doesn't matter, it just looks like that, in fact there are only two commonly used parameters: prev and cur. Next, let's follow the example to see the specific usage~

2. Examples

First provide an original array:

var arr = [3,9,4,3,6,0,9];

There are many ways to achieve the following requirements, including the solution method using reduce(), which is also a relatively simple way to implement.

1. Find the sum of array items

var sum = arr.reduce(function (prev, cur) {
    return prev + cur;
},0);

Since the initial value 0 is passed in, the value of prev is 0 at the beginning, and the value of cur is the first item 3 in the array. After addition, the return value is 3 as the prev value of the next round of callback, and then it continues to be added to the next array item, and so on, until the sum of all array items is completed and returned.

2. Find the maximum value of an array item

var max = arr.reduce(function (prev, cur) {
    return Math.max(prev,cur);
});

Since no initial value is passed in, the value of prev is 3, the first item in the array, and the value of cur is 9, the second item in the array. After taking the maximum value of the two values, we continue to enter the next round of callbacks.

3. Array deduplication

var newArr = arr.reduce(function (prev, cur) {
    prev.indexOf(cur) === -1 && prev.push(cur);
    return prev;
},[]);

The basic principles of implementation are as follows:

① Initialize an empty array ② Search the first item in the array that needs to be deduplicated in the initialization array. If it is not found (it will definitely not be found in an empty array), add the item to the initialization array ③ Search the second item in the array that needs to be deduplicated in the initialization array. If it is not found, add the item to the initialization array ④ ...
⑤ Search the nth item in the array that needs to be deduplicated in the initialization array. If it is not found, add the item to the initialization array. ⑥ Return the initialization array.

3. Other related methods

1. reduceRight()

The usage of this method is actually the same as reduce(), except that the traversal order is reversed. It starts from the last item in the array and traverses forward to the first item.

2. forEach(), map(), every(), some(), and filter()

For more details, please click → Introduction to array traversal forEach() and map() methods in JavaScript and compatible writing methods

Key points summary:

reduce() is an array merging method. Like forEach(), map(), filter() and other iteration methods, it will traverse each item in the array. However, reduce() can simultaneously calculate the results of the previous array item traversal and the current traversal item, which is unattainable by other iteration methods.

First look at the w3c grammar

array.reduce(function(total, currentValue, currentIndex, arr), initialValue);
/*
  total: required. The initial value, or the return value after the calculation is completed.
  currentValue: required. The current element.
  currentIndex: Optional. The index of the current element;                     
  arr: Optional. The array object to which the current element belongs.
  initialValue: optional. The initial value passed to the function is equivalent to the initial value of total.
*/

Common usage

Array sum

const arr = [12, 34, 23];
const sum = arr.reduce((total, num) => total + num);
<!-- Set the initial value to sum -->
const arr = [12, 34, 23];
const sum = arr.reduce((total, num) => total + num, 10); // Sum with 10 as the initial value<!-- Object array summation-->
var result = [
  { subject: 'math', score: 88 },
  { subject: 'chinese', score: 95 },
  { subject: 'english', score: 80 }
];
const sum = result.reduce((accumulator, cur) => accumulator + cur.score, 0); 
const sum = result.reduce((accumulator, cur) => accumulator + cur.score, -10); // Total score minus 10 points

Advanced usage: Usage in array objects

const a = [23,123,342,12];
const max = a.reduce(function(pre,cur,inde,arr){return pre>cur?pre:cur;}); // 342
<!-- For example, generate "the eldest, the second and the third" -->
const objArr = [{name: 'Old One'}, {name: 'Old Two'}, {name: 'Old Three'}];
const res = objArr.reduce((pre, cur, index, arr) => {
  if (index === 0) {
    return cur.name;
  }
  else if (index === (arr.length - 1)) {
    return pre + '和' + cur.name;
  }
  else {
    return pre + '、' + cur.name;
  }
}, '');

Find the number of times a letter appears in a string

const str = 'sfhjasfjgfasjuwqrqadqeiqsajsdaiwqdaklldflas-cmxzmnha';
const res = str.split('').reduce((accumulator, cur) => {accumulator[cur] ? accumulator[cur]++ : accumulator[cur] = 1; return accumulator;}, {});

Array to Object

<!-- Convert to an array according to certain rules-->

var arr1 = [2, 3, 4, 5, 6]; // Square each value var newarr = arr1.reduce((accumulator, cur) => {accumulator.push(cur * cur); return accumulator;}, []);

Advanced UsageMulti-dimensional overlay execution operations

<!-- Take out the stream according to the id -->

var streams = [{name: 'Technology', id: 1}, {name: 'Design', id: 2}];
var obj = streams.reduce((accumulator, cur) => {accumulator[cur.id] = cur; return accumulator;}, {});

Advanced UsageMulti-dimensional overlay execution operations

<!-- The weight of each subject is different, please give the result-->

var result = [
  { subject: 'math', score: 88 },
  { subject: 'chinese', score: 95 },
  { subject: 'english', score: 80 }
];
var dis = {
    math: 0.5,
    Chinese: 0.3,
    English: 0.2
};
var res = result.reduce((accumulator, cur) => dis[cur.subject] * cur.score + accumulator, 0);

<!-- Increase the difficulty, the exchange rate of goods in different countries is different, find the total price-->

var prices = [{price: 23}, {price: 45}, {price: 56}];
var rates = {
  us: '6.5',
  eu: '7.5',
};
var initialState = {usTotal: 0, euTotal: 0};
var res = prices.reduce((accumulator, cur1) => Object.keys(rates).reduce((prev2, cur2) => {
  console.log(accumulator, cur1, prev2, cur2);
  accumulator[`${cur2}Total`] += cur1.price * rates[cur2];
  return accumulator;
}, {}), initialState);

var manageReducers = function() {
  return function(state, item) {
    return Object.keys(rates).reduce((nextState, key) => {
        state[`${key}Total`] += item.price * rates[key];
        return state;
      }, {});
  }
};
var res1 = prices.reduce(manageReducers(), initialState);

Flatten a 2D array

var arr = [[1, 2, 8], [3, 4, 9], [5, 6, 10]];
var res = arr.reduce((x, y) => x.concat(y), []);

Object array deduplication

const hash = {};
  chatlists = chatlists.reduce((obj, next: Object) => {
    const hashId = `${next.topic}_${next.stream_id}`;
    if (!hash[hashId]) {
      hash[`${next.topic}_${next.stream_id}`] = true;
      obj.push(next);
    }
    return obj;
  }, []);

compose function
Redux compose source code implementation

function compose(...funs) {
    if (funs.length === 0) {
        return arg => arg;
    }
    if (funs.length === 1) {
       return funs[0];
    }
    return funs.reduce((a, b) => (...arg) => a(b(...arg)))

}


This is the end of this article about the summary of the use of the reduce() method in JS. For more relevant js reduce() method content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of the basic usage of JavaScript reduce
  • JavaScript Array reduce() Method
  • Implementation and usage examples of JS array push, unshift, pop, and shift methods
  • Example of how to use pop in JS
  • js uses class to encapsulate pop pop-up window components
  • Reduce method and pop method in javascript array

<<:  A brief understanding of the difference between MySQL union all and union

>>:  Nginx improves access speed based on gzip compression

Recommend

Web page printing thin line table + page printing ultimate strategy

When I was printing for a client recently, he aske...

Vue implements the countdown component for second kills

This article shares the specific code of Vue to i...

Example of using mycat to implement MySQL database read-write separation

What is MyCAT A completely open source large data...

Summary of essential Docker commands for developers

Table of contents Introduction to Docker Docker e...

Pure CSS to achieve candle melting (water droplets) sample code

Achieve results Implementation ideas The melting ...

Tips for using top command in Linux

First, let me introduce the meaning of some field...

MYSQL performance analyzer EXPLAIN usage example analysis

This article uses an example to illustrate the us...

Jenkins Docker static agent node build process

A static node is fixed on a machine and is starte...

Detailed explanation of Mysql logical architecture

1. Overall architecture diagram Compared to other...

WeChat applet development practical skills: data transmission and storage

Combining the various problems I encountered in m...

Five solutions to cross-browser problems (summary)

Brief review: Browser compatibility issues are of...

Solve the margin: top collapse problem in CCS

The HTML structure is as follows: The CCS structu...

The latest mysql-5.7.21 installation and configuration method

1. Unzip the downloaded MySQL compressed package ...

Introduction to Linux system swap space

Swap space is a common aspect of computing today,...