Search code examples
javascriptarrays

How to count duplicate value in an array in javascript


Currently, I got an array like that:

var uniqueCount = Array();

After a few steps, my array looks like that:

uniqueCount = [a,b,c,d,d,e,a,b,c,f,g,h,h,h,e,a];

How can I count how many a,b,c are there in the array? I want to have a result like:

a = 3
b = 1
c = 2
d = 2

etc.


Solution

  • 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<br>');
                }
                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