in Code

Here’s another fun code challenge from Coderbyte:

Using the JavaScript language, have the function SimpleMode(arr) take the array of numbers stored in arr and return the number that appears most frequently (the mode). For example: if arr contains [10, 4, 5, 2, 4] the output should be 4. If there is more than one mode return the one that appeared in the array first (ie. [5, 10, 10, 6, 5] should return 5 because it appeared first). If there is no mode return -1. The array will not be empty.


Here are some test cases:

Input = 5,5,2,2,1O Output = 5
Input = 3,4,1,6,10 Output = -1

Here’s my solution collapsed:

function SimpleMode(arr) {
    var highest = 1;
    var mostFrequently = -1;

    for ( var i = 0; i < arr.length; i++ ) {
        var count = 0;

        for ( var j = 0; j < arr.length; j++ ) {
            if ( arr[i] == arr[j] ) {
                count++;
            }
        }

        if ( count > highest ) {
            highest = count;
            mostFrequently = arr[i];
        }
    }

    return mostFrequently;
};

To start, I setup two variables. The variable highest would hold the current highest frequency. For example, if the digit 2 appeared three times, highest would be three. To start, I could safely set this to 1 since the array was promised not to be empty and a digit would have to appear once by default. The mostFrequently variable held the actual digit that I wanted to return at the end (the one that appeared most frequently). Since I wanted to return -1 if there wasn’t a mode, I set mostFrequently to -1 at the beginning.

Next, I started a for loop that would loop over the array. Within that for loop, I created another for loop comparing the item to every other item in the array. If the items matched, I incremented my counter variable.

for ( var i = 0; i < arr.length; i++ ) {
    var count = 0;

    for ( var j = 0; j < arr.length; j++ ) {
        if ( arr[i] == arr[j] ) {
            count++;
        }
    }
}

Once the comparison for loop was finished, I compared the value of count to the value of highest. If it was greater, I replaced the value of highest with count and set the mostFrequently variable to the current array item.

if ( count > highest ) {
    highest = count;
    mostFrequently = arr[i];
}

Solve it a different way? I want to hear it. Let me know in the comments!

Leave a Thought