Most Frequent

Completed Code

var arr=[ 1, 'fish', 2, 'fish', 'red', 'fish', 'blue', 'fish'];
var mf=1;
var m=0;
var item;
for (var i=0; i<arr.length; i++)
{
    for (var j=i; j<arr.length; j++)
    {
        if (arr[i] == arr[j])
        m++;
        if (mf<m)
        {
            mf=m;
            item = arr[i];
        }
    }
    m=0;
}
console.log(item+" (" +mf +" times)");

Explanation

  • Variables

    • mf - the running total of occurrences of the current most frequent element

    • m - the number of occurrences for the element you are currently testing

    • item - the most frequent element

  • Steps

    1. mf is set to 1. Any element in the array occurs at least once.

    2. We start with the first element in the array, 1. m becomes 1, as there is an occurrence of the element at least once.

    3. We loop through the array looking for other instances of the element, but there aren't any.

    4. mf is not changed because there is only one occurrence of our first element.

    5. m is reset back to 0 (zero) and we move on to next element.

    6. Steps 2-5 are repeated, except this time 'fish' is the element being tested. There are 4 occurrences of the element in our array so m is now 4. 4 is greater than 1, so mf takes the value of m and item becomes fish.

    7. The process is repeated using 'red' and 'blue'. Each of the elements only occur once, so nothing changes. Our most frequent element is 'fish' with 4 occurrences.

Last updated