Get the element with the highest occurrence in an array

后端 未结 30 1629
野性不改
野性不改 2020-11-22 11:17

I\'m looking for an elegant way of determining which element has the highest occurrence (mode) in a JavaScript array.

For example, in

[\'pear\', \'a         


        
30条回答
  •  旧巷少年郎
    2020-11-22 12:05

    var mode = 0;
    var c = 0;
    var num = new Array();
    var value = 0;
    var greatest = 0;
    var ct = 0;
    

    Note: ct is the length of the array.

    function getMode()
    {
        for (var i = 0; i < ct; i++)
        {
            value = num[i];
            if (i != ct)
            {
                while (value == num[i + 1])
                {
                    c = c + 1;
                    i = i + 1;
                }
            }
            if (c > greatest)
            {
                greatest = c;
                mode = value;
            }
            c = 0;
        }
    }
    

提交回复
热议问题