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.
var a = b || c;
is a common idiom in JavaScript. What it means is:
b
is a truthy value, a
will receive b
.b
is a falsy value, a
will receive c
.(Look up "JavaScript truthy and falsy values" to understand this. Basically there are 6 things in JavaScript that are falsy. Everything else is truthy).
This is basically counting the number of occurrences of something.
If there wasn't a value assigned for c[arr[i]]
, it will be undefined
. Being undefined
, the expression (c[arr[i]] || 0)
would result in 0
, because undefined
is a falsy value. Then, 0 + 1
results in 1
. c[arr[i]]
is now 1
.
On the other hand, if there was a value assigned for c[arr[i]]
, then (c[arr[i]] || 0)
would result that same value (let's say, 1
, for instance). So (c[arr[i]] || 0)
is then 1
, since c[arr[i]]
is 1
and 1 || 0
would result in 1
, since 1
is a truthy value. Then you have 1 + 1
and c[arr[i]]
is now 2
.
You are counting occurrences of something. You started with 0
, then 1
, then 2
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With