[Javascript] Advanced Reduce: Common Mistakes

Take away:

  • Always check you ruturn the accumulator
  • Always pass in the inital value
var data = ["vote1", "vote2", "vote1", "vote2"];

var reducer = function(acc, value){
   if(acc[value]){
     acc[value] = acc[value] + 1;
   }else{
     acc[value] = 1;
   }
  
  return acc;
};

var res = data.reduce(reducer ,{});

console.log(res);
原文地址:https://www.cnblogs.com/Answer1215/p/5008972.html