一尘不染

如何在JavaScript数组中计算重复值

javascript

目前,我得到了这样的数组:

var uniqueCount = Array();

经过几步,我的数组如下所示:

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

我如何计算数组中有多少个a,b,c?我想要一个类似的结果:

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

等等


阅读 249

收藏
2020-04-25

共1个答案

一尘不染

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();
2020-04-25