I am very new to programming, so forgive me for being such a noob. Any input is much appreciated. The challenge asks to find the mode in an array of numbers. Here is the code:
function findMode(arr) {
var c = {};
for (var i = 0; i < arr.length; i++) {
c[arr[i]] = (c[arr[i]] || 0) + 1;
}
var mode;
var max = 0;
for (var e in c) {
if (c[e] > max) {
mode = e;
max = c[e];
}
}
return mode * 1;
}
So for example if you have an array of [1,1,5,5,7,10,3,3,3,3]
, it makes an object of {'1':2, '3':4, '5':2, '7':1, '10':1}
. The code below it( for(e in c)
) I understand it. Function basically returns the mode which is 3. What I am confused about is the following code:
c[arr[i]] = (c[arr[i]] || 0) + 1;
This code is responsible for creating the following object:
{'1':2, '3':4, '5':2, '7':1, '10':1}
Can someone please explain how it does that? How does it make the list of objects and keep count of each object name? I am very confused by it.