JavaScript array (array) reduce method detailed

1. Grammar

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

arr : the original array;
prev : the return value when the callback was called last time, or the initial value init;
cur : the array element currently being processed ;
index : 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 : initial value

In fact, there are only two commonly used parameters: 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
<!-- 设定初始值求和 -->
var sum = arr.reduce((prev,cur)=>{
    
    
  return prev + cur;
},10) // 20


<!-- 对象数组求和 -->
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
<!--  总分扣除10-->
var sum = result.reduce((prev, cur) => prev + cur.score, -10);  // 240

2.2 Maximum value of array item

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

// 法2::Math.max(a,b,...,x,y)    返回数个数字中较大的值 
var max = arr.reduce(function (prev, cur) {
    
    
    return Math.max(prev,cur);
}); // 4

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]

The basic principle of realization is as follows:

① Initialize an empty array;
② Search for the first item in the array that needs to be deduplicated in the initialization array. If it can't be found (it's definitely not found in the empty array), add the item to the initialization array;
③ Search for the second item in the array that needs to be deduplicated in the initialization array, if it is not found, continue to add the item to the initialization array;
④ ……
⑤ The nth item in the array that needs to be deduplicated Search in the initialization array, if not found, continue to add the item to the initialization array;
⑥ Return this initialization array;

2.4 Use in array objects

const objArr = [{
    
    name: '唐僧'},{
    
    name: '悟空'}, {
    
    name: '八戒'}, {
    
    name: '沙僧'}];

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;
  }
}, ''); // 唐僧、悟空、八戒和沙僧

2.5 Number of occurrences 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}

2.6 Array to Array (convert to array according to certain rules)

var arr = [1, 2, 3,]; // 每个值的平方

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

2.7 Array to Object

var streams = [{
    
    name: '开发', id: 1}, {
    
    name: '设计', id: 2}];

var obj = streams.reduce((prev, cur) => {
    
    
  prev[cur.id] = cur.name;
  return prev;
}, {
    
    }); // {1: "开发", 2: "设计"}

2.8 Multi-dimensional overlay execution operation

<!-- 各科成绩占比重不一样, 求结果 -->

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

<!-- 加大难度, 商品对应不同国家汇率不同,求总价格 -->
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];
        return state;
      }, {
    
    });
  }
};

var res1 = prices.reduce(manageReducers(), initialState);  // {usTotal: 1612, euTotal: 1860}

2.9 Multi-dimensional overlay execution operation

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]

2.10 Array object de-duplication

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);
  return prev;
}, []); 
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); 
  }
  return prev;
}, []); 
console.log(obj,newArr); 
// {A: 1, B: 3, C: 4}  [{id: 1, name: 'A'}, {id: 3,name: 'B'}, {id: 4,name: 'C'}] 

3. reduceRight()

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

Guess you like

Origin blog.csdn.net/ZYS10000/article/details/109900850