Finding out how many times an array element appears

前端 未结 6 1312
既然无缘
既然无缘 2020-12-01 14:50

I am new to JavaScript, I have been learning and practicing for about 3 months and hope I can get some help on this topic. I\'m making a poker game and what I\'m trying to d

6条回答
  •  半阙折子戏
    2020-12-01 15:05

    Well..

    var a = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4].reduce(function (acc, curr) {
      if (typeof acc[curr] == 'undefined') {
        acc[curr] = 1;
      } else {
        acc[curr] += 1;
      }
    
      return acc;
    }, {});
    
    // a == {2: 5, 4: 1, 5: 3, 9: 1}
    

    from here: Counting the occurrences of JavaScript array elements

    Or you can find other solutions there, too..

提交回复
热议问题