Javascript count duplicates and uniques and add to array

前端 未结 5 1581
无人及你
无人及你 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:49

    You can use reduce and return object

    var ar = ['a', 'a', 'b', 'c', 'c'];
    var result = ar.reduce(function(r, e) {
      r[e] = (r[e] || 0) + 1;
      return r;
    }, {});
    
    console.log(result)

    You can also first create Object and then use forEach add properties and increment values

    var ar = ['a', 'a', 'b', 'c', 'c'], result = {}
    ar.forEach(e => result[e] = (result[e] || 0)+1);
    console.log(result)

提交回复
热议问题