SoFunction
Updated on 2025-02-28

Example of usage of reduce in JavaScript

Preface

For a long time in the past, I have been having difficulty understanding the specific usage of reduce() method, and I rarely use it in normal times. In fact, if you can really understand it, we can actually use it in many places. So today we will briefly talk about the usage of reduce() in JS.

1. Syntax

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

in,

  • arr represents the original array;
  • prev represents the return value when the callback was last called, 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 an init value is provided, the index is 0, otherwise the index is 1;
  • init represents the initial value.

Does it seem complicated? It doesn't matter, it just looks like it. 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 a raw array:

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

There are many ways to implement the following requirements, including the solution using reduce(), which is also a relatively concise implementation.

1. Find the sum of array items

var sum = (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 of the array. After addition, the return value is 3 as the prev value of the next callback, and then continue to add with the next array item, and so on until the sum of all array items is completed and returned.

2. Find the maximum value of the array item

var max = (function (prev, cur) {
    return (prev,cur);
});

Since no initial value is passed in, the value of prev at the beginning is the first item 3 of the array, and the value of cur is the second item 9 of the array. After taking the maximum value of the two values, it continues to enter the next callback.

3. Deduplication of array

var newArr = (function (prev, cur) {
    (cur) === -1 && (cur);
    return prev;
},[]);

The basic principles of implementation are as follows:

① Initialize an empty array

② Look up the first item in the array that needs to be deduplicated in the initialization array. If it cannot be found (it is definitely not found in the empty array), add the item to the initialization array.

③ Look up the second item in the array that needs to be deduplicated in the initialization array. If it cannot be found, continue to add the item to the initialization array.

④ ……

⑤ Look up the nth item in the array that needs to be deduplicated in the initialization array. If it cannot be found, continue to add the item to the initialization array.

⑥ Return this initialization array

3. Other related methods

1. reduceRight()

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

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

Please click →Briefly describe the usage of forEach(), map(), every(), some() and filter()

Key summary:

reduce() is an array merge method. Like iterative methods such as forEach(), map(), filter(), etc., iterates each item in the array, but reduce() can simultaneously compute the results generated by the previous array item traversal with the current traversal item, which is something that other iterative methods cannot achieve.

First look at the w3c syntax

(function(total, currentValue, currentIndex, arr), initialValue);
/*
   total: Required.  The initial value, or the return value after calculation.
   currentValue: Required.  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 = ((total, num) => total + num);
<!-- Set initial values ​​to sum -->
const arr = [12, 34, 23];
const sum = ((total, num) => total + num, 10);  // Sum with 10 as the initial value<!-- Sum of object arrays -->
var result = [
  { subject: 'math', score: 88 },
  { subject: 'chinese', score: 95 },
  { subject: 'english', score: 80 }
];
const sum = ((accumulator, cur) => accumulator + , 0); 
const sum = ((accumulator, cur) => accumulator + , -10);  // Total points deduction10point

Maximum value of array

const a = [23,123,342,12];
const max = (function(pre,cur,inde,arr){return pre>cur?pre:cur;}); // 342

Advanced usage

Usage in array objects

<!-- For example, generation“Boss、The second and the third” -->
const objArr = [{name: 'Boss'}, {name: 'Die'}, {name: 'The third brother'}];
const res = ((pre, cur, index, arr) => {
  if (index === 0) {
    return ;
  }
  else if (index === ( - 1)) {
    return pre + 'and' + ;
  }
  else {
    return pre + '、' + ;
  }
}, '');

Find the number of times the letter appears in a string

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

Array to array

<!-- Convert to an array according to certain rules -->
var arr1 = [2, 3, 4, 5, 6]; // Square of each valuevar newarr = ((accumulator, cur) => {(cur * cur); return accumulator;}, []);

Array to object

<!-- according toid take outstream -->
var streams = [{name: 'technology', id: 1}, {name: 'design', id: 2}];
var obj = ((accumulator, cur) => {accumulator[] = cur; return accumulator;}, {});

Advanced Usage

Multi-dimensional overlay execution

<!-- The proportion of scores in each subject is different, Find 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 = ((accumulator, cur) => dis[] *  + accumulator, 0);
var prices = [{price: 23}, {price: 45}, {price: 56}];
var rates = {
  us: '6.5',
  eu: '7.5',
};
var initialState = {usTotal:0, euTotal: 0};
var res = ((accumulator, cur1) => (rates).reduce((prev2, cur2) => {
  (accumulator, cur1, prev2, cur2);
  accumulator[`${cur2}Total`] +=  * rates[cur2];
  return accumulator;
}, {}), initialState);

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

Flat a two-dimensional array

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

Deduplication of object array

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

compose function

redux compose source code implementation

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

}

Summarize

This is the end of this article about the usage example of reduce() in JavaScript. For more information about the usage content of JS reduce(), please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!