[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);

 

posted @ 2015-12-01 01:31  Zhentiw  阅读(154)  评论(0编辑  收藏  举报