How to count duplicate value in an array in javascript

前端 未结 28 1411
后悔当初
后悔当初 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:34

    I stumbled across this (very old) question. Interestingly the most obvious and elegant solution (imho) is missing: Array.prototype.reduce(...). All major browsers support this feature since about 2011 (IE) or even earlier (all others):

    var arr = ['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a'];
    var map = arr.reduce(function(prev, cur) {
      prev[cur] = (prev[cur] || 0) + 1;
      return prev;
    }, {});
    
    // map is an associative array mapping the elements to their frequency:
    document.write(JSON.stringify(map));
    // prints {"a": 3, "b": 2, "c": 2, "d": 2, "e": 2, "f": 1, "g": 1, "h": 3}

提交回复
热议问题