This is the 17th day of my participation in Gwen Challenge

1. Grammar

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

Arr: primitive array;

Prev: the return value when the callback was last called, or the initial value init;

Cur: The array element currently being processed;

Index: The index of the array element being processed, 0 if init is provided, 1 otherwise;

Init: indicates the initial value

There are only two parameters commonly used: prev and CUR.

2. Common usage

2.1 Array Summation

var arr = [1.2.3.4];

var sum = arr.reduce((prev,cur) = >{
   return prev + cur;
}) / / 10<! Set initial value summation -->var sum = arr.reduce((prev,cur) = >{
  return prev + cur;
},10) / / 20<! Object array summation -->var result = [
  { subject: 'math'.score: 80 },
  { subject: 'chinese'.score: 90 },
  { subject: 'english'.score: 80}];var sum = result.reduce((prev, cur) = > prev + cur.score, 0); / / 250<! -- Total score deduction10Points - >var sum = result.reduce((prev, cur) = > prev + cur.score, -10);  / / 240
Copy the code

2.2 Maximum value of array items

var arr = [1.2.3.4];
/ / method 1:
var max = arr.reduce(function (prev, cur) {
    return prev > cur ? prev : cur;
}); / / 4

// Method 2: :Math. Max (a,b... ,x,y) returns the greater of several numbers
var max = arr.reduce(function (prev, cur) {
    return Math.max(prev,cur);
}); / / 4
Copy the code

2.3 Array deduplication

var arr = [1.2.3.4.2.1.5];

var newArr = arr.reduce((prev, cur) = > {
    prev.indexOf(cur) === -1 && prev.push(cur);
    return prev;
},[]); // [1, 2, 3, 4, 5]
Copy the code

The basic principle of implementation is as follows:

Initialize an empty array.

② Look for the first item in the array to be reprocessed in the initialization array. If it cannot be found, add the item to the initialization array.

③ Look for the second item in the array to be reprocessed in the initialization array. If no item is found, add the item to the initialization array.

(4)…

⑤ Look for the NTH item in the array that needs to be reprocessed in the initialization array. If it cannot be found, add the item to the initialization array.

⑥ Return the initialization array;

2.4 used in array objects

const objArr = [{name: "Tang's monk}, {name: 'wukong'}, {name: 'pig'}, {name: '沙僧'}];

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; }},' '); // Tang Seng, Wukong, Bajie and Sand Seng
Copy the code

2.5 Number of letters in a string

const str = 'sfhjasfjgfarda-cm';

const res = str.split(' ').reduce((prev, cur) = > {
  prev[cur] ? prev[cur]++ : prev[cur] = 1; 
  return prev;
}, {}); // {-: 1,a: 3,c: 1,d: 1,f: 3,g: 1,h: 1,j: 2,m: 1,r: 1,s: 2}
Copy the code

2.6 Converting an Array to an Array (Converting an array according to certain rules)

var arr = [1.2.3,]; // Square each value

var newarr = arr.reduce((prev, cur) = > {
  prev.push(cur * cur);
   returnprev; } []);/ / [1, 4, 9]
Copy the code

2.7 Array to object

var streams = [{name: 'development'.id: 1}, {name: 'design'.id: 2}];

var obj = streams.reduce((prev, cur) = > {
  prev[cur.id] = cur.name;
  return prev;
}, {}); // {1: "development ", 2:" design "}
Copy the code

2.8 Multi-dimensional superposition operation

<! -- The proportion of each subject is not the same, find the result -->var result = [
  { subject: 'math'.score: 80 },
  { subject: 'chinese'.score: 90 },
  { subject: 'english'.score: 80}];var dis = {
  math: 0.5.chinese: 0.3.english: 0.2
};
var res = result.reduce((prev, cur) = > dis[cur.subject] * cur.score + prev, 0); / / 83<! -- To increase the difficulty, the commodity corresponds to different exchange rates of different countries, and the total price is calculated -->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((prev1, cur1) = > Object.keys(rates).reduce((prev2, cur2) = > {
  prev1[`${cur2}Total`] += cur1.price * rates[cur2];
  return prev1;
}, {}), initialState);

var manageReducers = function() {
  return function(state, item) {
    return Object.keys(rates).reduce((nextState, key) = > {
        state[`${key}Total`] += item.price * rates[key];
        returnstate; }, {}); }};var res1 = prices.reduce(manageReducers(), initialState);  // {usTotal: 1612, euTotal: 1860}
Copy the code

2.9 Multi-dimensional superposition to perform operations

var arr = [[1.2.8], [3.4.9], [5.6.10]].var res = arr.reduce((prev, cur) = > prev.concat(cur), []);  // [1, 2, 8, 3, 4, 9, 5, 6, 10]
Copy the code

2.10 Array objects are deduplicated

var arr = [{id: 1.name: 'A'}, {id: 2.name: 'A'}, {id: 3.name: 'B'}, {id: 4.name: 'C'}];

var obj = {};

var newArr = arr.reduce((prev, cur) = > {
  obj.hasOwnProperty(cur.name) ? ' ': obj[cur.name] = true && prev.push(cur);
  returnprev; } []);console.log(obj,newArr);
// {A: 1, B: 2, C: 3} [{id: 1, name: 'A'}, {id: 3,name: 'B'}, {id: 4,name: 'C'}]

var newArr = arr.reduce((prev, cur) = > {
  if(! obj.hasOwnProperty(cur.name)){ obj[cur.name] = cur.id; prev.push(cur); }returnprev; } []);console.log(obj,newArr); 
// {A: 1, B: 3, C: 4} [{id: 1, name: 'A'}, {id: 3,name: 'B'}, {id: 4,name: 'C'}]
Copy the code

3. reduceRight()

This method is used in the same way as reduce(), but in reverse order, starting from the last item of the array and moving forward to the first item.