Summary of reduce of method usage in JS

  • 2021-11-13 06:36:49
  • OfStack

Catalog 1. Syntax 2. Example 3. Other related methods

For a long time in the past, it was difficult for me to understand the specific usage of reduce (), and I seldom used it at ordinary 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. Grammar

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

Among them,
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 denotes the index of the array element currently being processed. If init is provided, the index is 0, otherwise the index is 1;
init represents the initial value.

Does it look complicated? It doesn't matter, it just seems that 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 realize the following requirements, including the solution using reduce (), which is a relatively simple one.

1. Sum Array Items


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

Since the initial value of 0 is passed in, the value of prev is 0 at the beginning, and the value of cur is 3 in the first item of the array. After adding, the return value is 3 as the value of prev in the next round of callback, and then continues to add with the next item of the array, and so on until all the items of the array are summed and returned.

2. Maximize Array Items


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

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

3. Array de-duplication


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

The basic principle of implementation is as follows:

① Initialize an empty array
The first item in the array that needs to be reprocessed is searched in the initialization array. If it cannot be found (it must not be found in the empty array), the item is added to the initialization array
Find the second item in the array that needs to be reprocessed in the initialization array, and if it can't be found, continue to add the item to the initialization array
(4) …
5. Find the n item in the array that needs to be reprocessed in the initialization array. If it cannot be found, continue to add the item to the initialization array
Return this initialization array

3. Other relevant methods

1. reduceRight()

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

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

For details, please stamp the array traversal forEach () and map () methods in → JavaScript and introduce the compatible writing methods

Key summary:

reduce () is a merging method of arrays, and forEach (), map (), filter () and other iterative methods will traverse each item of arrays, but reduce () can simultaneously traverse the results of the previous array items and the current traversal items, which is beyond the reach of other iterative methods

Look at the syntax of w3c first


array.reduce(function(total, currentValue, currentIndex, arr), initialValue);
/*
  total:  Necessary. Initial value ,  Or the return value after the calculation. 
  currentValue :   Necessary. 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 total The initial value of the. 
*/

Common usage

Array summation


const arr = [12, 34, 23];
const sum = arr.reduce((total, num) => total + num);
<!--  Set the initial value sum  -->
const arr = [12, 34, 23];
const sum = arr.reduce((total, num) => total + num, 10);  //  With 10 Sum 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 deduction 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 "boss, old" 2 And the old 3 "  -->

const objArr = [{name: ' Boss '}, {name: ' Old 2'}, {name: ' Old 3'}];
const res = objArr.reduce((pre, cur, index, arr) => {
  if (index === 0) {
    return cur.name;
  }
  else if (index === (arr.length - 1)) {
    return pre + ' And ' + cur.name;
  }
  else {
    return pre + ' , ' + cur.name;
  }
}, '');

Find the number of letters 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 the rule of 1-- >


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

Advanced usage multidimensional overlay execution operation

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


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

Advanced usage
Multidimensional overlay execution operation

< ! --The scores of each subject account for less than one sample, and the results are sought- >


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

< ! -Increase the difficulty, goods correspond to different exchange rates in different countries, and seek 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);

Flat 1 2-D array


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

Object array deduplication


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

compose function
redux compose source code implementation


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

Related articles: