(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
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 atdarray[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
Optionally, I’d recommend using a Map since objects are meant to be fixed shapes whereas Maps can change shape as you are using.
Your code posted here didn’t work as expected. I made a few changes to make it work.
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 = {}’ .