How to count duplicate value in an array in javascript

前端 未结 28 2082
后悔当初
后悔当初 2020-11-22 06:07

Currently, I got an array like that:

var uniqueCount = Array();

After a few steps, my array looks like that:

uniqueCount =          


        
28条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-22 06:30

    You can have an object that contains counts. Walk over the list and increment the count for each element:

    var counts = {};
    
    uniqueCount.forEach(function(element) {
      counts[element] = (counts[element] || 0) + 1;
    });
    
    for (var element in counts) {
      console.log(element + ' = ' + counts[element]);
    } 
    

提交回复
热议问题