How to count duplicate value in an array in javascript

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

    function count() {
        array_elements = ["a", "b", "c", "d", "e", "a", "b", "c", "f", "g", "h", "h", "h", "e", "a"];
    
        array_elements.sort();
    
        var current = null;
        var cnt = 0;
        for (var i = 0; i < array_elements.length; i++) {
            if (array_elements[i] != current) {
                if (cnt > 0) {
                    document.write(current + ' comes --> ' + cnt + ' times
    '); } current = array_elements[i]; cnt = 1; } else { cnt++; } } if (cnt > 0) { document.write(current + ' comes --> ' + cnt + ' times'); } } count();

    Demo Fiddle

    You can use higher-order functions too to do the operation. See this answer

提交回复
热议问题