Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Fareez Ahmed
31 PointsFinding the "Mode" of an Array.
Can folks share functions that are succinct/easy to understand, for finding the mode of an array? Assuming there is only one mode and there will be at least one.
I have stepped through a solution with a tutor but trying to re-read it after having done it is not useful.
1 Answer
Michael Jurgensen
8,341 PointsHi Fareez,
First create an empty object to hold the mode. Then create var max (this will be the mode value). Also create a var count to determine which number will be the max. You need to loop through each element in the array. First check the value of mode. If its value is null set it to 1. Otherwise increment the value. Then you want to determine if count is less than the value of mode.
function mode(input)
{
var mode = {};
var max = 0;
var count = 0;
input.forEach(function(e)
{
if (mode[e] == null)
{
mode[e] = 1;
}
else
{
mode[e]++;
}
if (count < mode[e])
{
max = e;
count = mode[e];
}
});
return max;
}
var input = [4,4,4,6,2,7,7,9,9];
alert(mode(input));
EDIT: Easier to understand solution.