count duplicates in array javascript

Posted by Paidboom - 4 months ago

How to count duplicate value in an array in javascript?

There are a couple of ways to count duplicate elements in a javascript array. by using the forEach or for loop. Iterate over the array using a for loop.

function count() {
    array_elements = ["a", "b", "c", "d", "e", "a", "b", "c", "f", "g", "h", "h", "h", "e", "a"];

    array_elements.sort();

    var active = null;
    var flag = 0;
    for (var i = 0; i < array_elements.length; i++) {
        if (array_elements[i] != active) {
            if (flag > 0) {
                document.write(active + ' comes --> ' + flag + ' times<br>');
            }
            active = array_elements[i];
            flag = 1;
        } else {
            flag++;
        }
    }
    if (flag > 0) {
        document.write(active + ' comes --> ' + flag + ' times');
    }

}

count();