Can someone walk me through this exercise? Write a JavaScript program to find the most frequent item of an array.
Using Array.prototype.reduce() and a temporary variable, You could do it this way (4 lines):
var arr2 = [3, 'a', 'a', 'a', 2, 3, 'a', 3, 'a', 2, 4, 9, 3];
var newArr = arr2.slice().sort(), most = [undefined, 0], counter = 0;
newArr.reduce(function(old, chr){
old == chr ? ++counter > most[1] && (most = [chr, counter]) : (counter = 1)
return chr
});
alert(most[0] + " ( "+most[1]+" times )");
Explanation Excuse my english.
Using Array.prototype.reduce() can simplify your work. The following function first sorts their characters as 22333349aaaaa, then this counts your characters in sequence. I created a temp variable most to store the data of the character most repeated.
Note This only works for items of single digits.