Nate
Nate

Reputation: 161

algorithm to find most repeated values in an array

I stumbled upon this code... I know it is not contributive to ask question like this but can someone please explain these to me in layman term? thank you so much

var arr1 = [3, 'a', 'a', 'a', 2, 3, 'a', 3, 'a', 2, 4, 9, 3];
var mf = 1;
var m = 0;
var item;
for (var i=0; i<arr1.length; i++)
{
    for (var j=i; j<arr1.length; j++)
    {
            if (arr1[i] == arr1[j])
             m++;
            if (mf<m)
            {
              mf=m; 
              item = arr1[i];
            }
    }
    m=0;
}
alert(item+" ( " +mf +" times ) ") ;

Upvotes: 0

Views: 83

Answers (1)

Tanuj Yadav
Tanuj Yadav

Reputation: 1277

In the code provided by you, what we are doing is

we start from the first element of the array and then using another for loop, we compare the current value with all the values of the array that come after it. If they are same then we increase the counter m by 1.
So, at the end of the for loop, we will have the frequency of the current value. Then we check whether it is the largest frequency, if yes then we store it in the variable mf.

So at last we will have the element which occurred most number of times in the array.

Upvotes: 1

Related Questions