Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Could someone please explain the looping process to add new properties to an object?

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.

like image 950
Yashar Feizi Avatar asked Mar 17 '23 06:03

Yashar Feizi


1 Answers

var a = b || c; is a common idiom in JavaScript. What it means is:

  1. if b is a truthy value, a will receive b.
  2. if 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.

like image 56
Rafael Eyng Avatar answered Apr 25 '23 19:04

Rafael Eyng