I have an issue where I try to count combinations. I try to solve it with JavaScript, but have some issues... Example for the different sets:
var colors = ["Yellow", "Blue"];
var decisions = ["Yes", "No"];
As a first step I create an empty object and try to fill it with the two arrays and initialize a counter for each combination:
var myObject = {};
for ( colorIndex in colors ) {
myObject[colors[colorIndex]] = {};
for ( decisionIndex in decisions ) {
myObject[color][decisions[decisionIndex]] = 0;
}
}
In a next step I try to count results I got - Example:
var color = "Yellow";
var decision = "Yes";
myObject[color][decision] += 1;
Debugging (what I tried)
However, the result I am getting is something like:
Yellow: {Yes: 0, No: 0, Yes: NaN}
When I try to debug whats happening then I make the observation that the variables shortcodes are as follows:
myObject.Yellow.Yes = 0
myObject.Yellow.No = 0
myObject.Yellow["Yes"] = NaN
At this point I am not sure if I left away anything important, but does anyone of you know whats going on? I thought the brackets and dot-notation should be equivalent, even though I don't know how the dot-notation has been created here, since Yes and No were strings...
Can you pinpoint me in a direction?
Thanks for reading this.
Edit: Change to forEach-loop:
Based on recommendations I changed the loop to:
var myObject = {};
colors.forEach(function(color) {
myObject[color] = {};
decisions.forEach(function(decision) {
myObject[color][decision] = 0;
});
});
However, the problem remains that I get the NaN
-case