skip to Main Content

(newbie question)

I am trying to figure it out why the following code works.

The goal is to create keys from array elements and a .count (number of times the ID appears in the range).

I am approaching it this way.

var darray = [["BM","BM","CC","DD","CC","HH","KK","CC"]];
var obj = {}

for(i=0;i<darray.length;i++){
 
    var codes= darray[i][0]
 
    if(obj[codes]){

       obj[codes].count +=1
    }
    else {
      obj[codes] = {count: 1}

    }
}

console.log(obj)
result example:
{
BM: {count:2},
CC: {count:3}

}

This returns the expected output,but my point is if I miss the else statement, then I get an empty object back and I do not understand why the initialization in the else statement resolves this.
Thanks,

I need to understand the underlying logic of object initialization

2

Answers


  1. Your code snippet will only execute the for loop once because it’s executing on the outer darray array length (i.e., 1). So it only looks at darray[0][0].

    You need to use the inner array (i.e., the first element of the darray) to loop through the keys.

    The second mistake in the code snippet is you need to swap the array query when getting the codes.

    If you don’t swap the query then you will get an index out of bounds error because it will go

    1. darray[0][0]
    1. darray[1][0] // out of bounds
    
    var darray = [["BM","BM","CC","DD","CC","HH","KK","CC"]];
    var obj = {}
    
    for(i=0;i<darray[0].length;i++){
     
        var codes= darray[0][i]
     
        if(obj[codes]){
    
           obj[codes].count +=1
        }
        else {
          obj[codes] = {count: 1}
    
        }
    }
    
    console.log(obj)

    Optionally, I’d recommend using a Map since objects are meant to be fixed shapes whereas Maps can change shape as you are using.

    Login or Signup to reply.
  2. Your code posted here didn’t work as expected. I made a few changes to make it work.

    var darray = ["BM", "BM", "CC", "DD", "CC", "HH", "KK", "CC"];
    var obj = {}
    
    for (i = 0; i < darray.length; i++) {
    
        var code = darray[i]
    
        if (obj[code]) {
            obj[code].count += 1
        } else {
            obj[code] = {
                count: 1
            }
        }
    }
    
    console.log(obj)

    I think your question is the following:

    Why doesn’t it work without the else?

    Well if we follow the logic, it checks if obj[code] exist, if not he creates this entry into the object. But if you never add this entry to the object, it will never be able to count up any value.

    BUT it has not much to do with object initialization as this actually happens in the second rule on ‘var obj = {}’ .

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search