Javascript count duplicates and uniques and add to array

前端 未结 5 1558
无人及你
无人及你 2021-01-26 10:29

I\'m trying to count duplicates in an array of dates and add them to a new array.

But i\'m only getting the duplicates and the amount of times they exist in the array. <

5条回答
  •  心在旅途
    2021-01-26 10:47

    For that, you can use .reduce:

    var arr = ['a','a', 'b', 'c', 'c'];
    var result = arr.reduce(function(p,c){
      if(p[c] === undefined)
        p[c] = 0;
      p[c]++;
      return p;
    },{});
    
    console.log(result);

提交回复
热议问题