0

I was studying the function in the answer below:

Get the element with the highest occurrence in an array

but I am saddened to see it doesn't work for me (on repl.it). All the values end up being NaN, no matter how I try to increment them on line 13. What's wrong?

function mode(array)
{
    if(array.length === 0)
        return null;
    var modeMap = {};
    var maxEl = array[0], maxCount = 1;
    for(var i = 0; i < array.length; i++)
    {
        var el = array[i];
        if(modeMap[el] === null)
                modeMap[el] = 1;
        else
            modeMap[el] = modeMap[el] + 1;  
        if(modeMap[el] > maxCount)
        {
            maxEl = el;
            maxCount = modeMap[el];
        }
    }
    console.log(modeMap)
    return maxEl;
}

mode([4,2,6,2,6,6,6,6,]);
Community
  • 1
  • 1
dwilbank
  • 2,470
  • 2
  • 26
  • 37

3 Answers3

3

Instead of comparing modeMap[el]=== null you should check against undefined.

http://plnkr.co/edit/BjVGw5sbQXamOknypnyM?p=preview

function mode(array)
{
    if(array.length === 0)
        return null;
    var modeMap = {};
    var maxEl = array[0], maxCount = 1;
    for(var i = 0; i < array.length; i++)
    {
        var el = array[i];
        if(modeMap[el] === undefined)
                modeMap[el] = 1;
        else
            modeMap[el] = modeMap[el] + 1; 

        if(modeMap[el] > maxCount)
        {
            maxEl = el;
            maxCount = modeMap[el];
        }
    }
    console.log(modeMap)
    return maxEl;
}

mode([4,2,6,2,6,6,6,6]);
lucuma
  • 18,247
  • 4
  • 66
  • 91
1

Looks like the problem is you're triple equals comparing to null, when you should be comparing against undefined:

if (modeMap[el] === undefined)

Since el isn't in modeMap, modeMap[el] will be undefined, not null.

Xymostech
  • 9,710
  • 3
  • 34
  • 44
0

The problem here is that you are checking strict equality === against null, while undefined is the value returned when you access a non-existent key in an Object.

The robust way to check whether a variable is undefined or not is:

if (typeof variable === "undefined") {
    // Do something
}

Checking against window.undefined (with ===) is not safe for JavaScript versions prior to 1.8.5, where it is writable. It is made non-writable from JavaScript version 1.8.5.

Community
  • 1
  • 1
nhahtdh
  • 55,989
  • 15
  • 126
  • 162