0

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 ) ") ;

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

but i still dont quite understand.. if (mf<m) (if mf is more than m, which is 1, means occurs more than once right?) { mf=m; (then assign mf as m?? this i dun understand...) item = arr1[i]; (here... how will the correct item (correct index of arr1) be assigned to item? } thank you so much again for further elaboration!
mf is the max frequency that we have found till now, and m is the frequency of the current element. so (mf<m) checks whether current frequency is greater then max frequency, if yes, then update current frequency. And in item we are storing the element that has maximum frequency. so whenever (mf<m) is true, we alfo need to update item.
@AhQuan you can mark it as correct if it was helpful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.