How to count duplicate value in an array in javascript

前端 未结 28 1370
后悔当初
后悔当初 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 06:17

    Declare an object arr to hold the unique set as keys. Populate arr by looping through the array once using map. If the key has not been previously found then add the key and assign a value of zero. On each iteration increment the key's value.

    Given testArray:

    var testArray = ['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a'];
    

    solution:

    var arr = {};
    testArray.map(x=>{ if(typeof(arr[x])=="undefined") arr[x]=0; arr[x]++;});
    

    JSON.stringify(arr) will output

    {"a":3,"b":2,"c":2,"d":2,"e":2,"f":1,"g":1,"h":3}
    

    Object.keys(arr) will return ["a","b","c","d","e","f","g","h"]

    To find the occurrences of any item e.g. b arr['b'] will output 2

提交回复
热议问题