Can someone walk me through this exercise? Write a JavaScript program to find the most frequent item of an array.
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 ) ");
I've been checking out some similar questions on stackoverflow, just can't find the answers that I want.
My questions are:
I don't understand why there needs to have two for loops.
Why the need for
mf
andm
. Seems a bit confusing.Is there other way of solution on this?