Advanced usage of reduce

This method takes two parameters:

        The function to be executed, the function to be executed can also pass in parameters, respectively

                prev: the return value of the last function call

                cur: current element

                index: current element index

                arr: the array to be traversed

                Initial value for function iteration

usage:

 ①, count the number of occurrences of each element in the array 

let names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];

let nameNum = names.reduce((pre,cur)=>{
  if(cur in pre){
    pre[cur]++
  }else{
    pre[cur] = 1 
  }
  return pre
},{})
console.log(nameNum); //{Alice: 2, Bob: 1, Tiff: 1, Bruce: 1}

②. Array deduplication

let arr = [1,2,3,4,4,1]
let newArr = arr.reduce((pre,cur)=>{
    if(!pre.includes(cur)){
      return pre.concat(cur)
    }else{
      return pre
    }
},[])
console.log(newArr);// [1, 2, 3, 4]

③, 2D to 1D

let arr = [[0, 1], [2, 3], [4, 5]]
let newArr = arr.reduce((pre,cur)=>{
    return pre.concat(cur)
},[])
console.log(newArr); // [0, 1, 2, 3, 4, 5]

 ④, the attribute summation in the object

var result = [
    {
        subject: 'math',
        score: 10
    },
    {
        subject: 'chinese',
        score: 20
    },
    {
        subject: 'english',
        score: 30
    }
];

var sum = result.reduce(function(prev, cur) {
    return cur.score + prev;
}, 0);
console.log(sum) //60

 ⑤, js merges the same items in the array object, and counts the number and

let list=[
  {
    id:11,
    name:'apple',
    num:2
  },
   {
    id:11,
    name:'apple',
    num:3
  },
   {
    id:22,
    name:'pig',
    num:2
  },
   {
    id:11,
    name:'apple',
    num:2
  },
]
 
list = list.reduce((obj, item) => {  
  let find = obj.find(i => i.id === item.id)  
 let _d = {  
    ...item,  
    frequency: 1  
  }  
  find ? (find.num+=item.num,find.frequency++ ): obj.push(_d)  
  return obj  
}, [])

 

 

 The road ahead is still long, fortunately the road is still long

Guess you like

Origin blog.csdn.net/weixin_45849072/article/details/119936498