This is what I am trying to do,
// declare an array with 16 items, each with intial value = 0
var countMe = [
["00", 0],
["01", 0],
["02", 0],
["03", 0],
["10", 0],
["11", 0],
["12", 0],
["13", 0],
["20", 0],
["21", 0],
["22", 0],
["23", 0],
["30", 0],
["31", 0],
["32", 0],
["33", 0]
];
// calculate number of items for each array item by adding +1 to its previous value
$.each(dataFruits, function (index, item) {
if (item.weight > -1 && item.quantity > -1) {
countMe["" + item.weight + item.quantity, 1][1] = countMe["" + item.weight + item.quantity, 1][1] + 1;
}
});
// go through array and call method for each array item whose value is more then zero
for (var i = 0; i < 3; i++) {
for (var j = 0; j < 3; j++) {
if (countMe["" + i + j, 1][1] > 0) {
CreateText(countMe["" + i + j, 1][1], "black", 33, countMe["" + i + j, 0][0]);
}
}
}
Issues
I am not able to get value of array
I am able to update its value
It doesn't throw any errors, just doesn't give me any value.
2 Answers 2
You are supposed to use a normal JavaScript object (key-value pairs) for this case.
// Create a JavaScript object
var countMe = {};
for (var i = 0; i < 4; i += 1) {
for (var j = 0; j < 4; j += 1) {
// Create new keys and initialize them with 0.
countMe["" + i + j] = 0;
}
}
console.log(countMe);
would be
{ '10': 0,
'11': 0,
'12': 0,
'13': 0,
'20': 0,
'21': 0,
'22': 0,
'23': 0,
'30': 0,
'31': 0,
'32': 0,
'33': 0,
'00': 0,
'01': 0,
'02': 0,
'03': 0 }
thus we created a JavaScript object and then you can count like this
$.each(dataFruits, function (index, item) {
if (item.weight > -1 && item.quantity > -1) {
countMe["" + item.weight + item.quantity]++;
}
});
here, countMe["" + item.weight + item.quantity]++ will increment the number corresponding to "" + item.weight + item.quantity. For example, if the weight is 1 and quantity is 2 then the value becomes countMe["12"] and the value against it will be incremented.
Now that you counted the values, you can call the function, like this
for (var i = 0; i < 4; i += 1) {
for (var j = 0; j < 4; j += 1) {
if (countMe["" + i + j] > 0) {
CreateText(countMe["" + i + j], "black", 33, "" + i + j);
}
}
}
Actual Problem
When you do
countMe["" + item.weight + item.quantity, 1]
the indexing part
"" + item.weight + item.quantity, 1
will always be evaluated to be 1, because the comma operator gives the last element in it as the result of the expression. You can confirm that like this
console.log((1, 2, 3, 4));
// 4
or
var a = (1, 2, 3, 4);
console.log(a);
// 4
So, you are always accessing ["01", 0] as that is the element at index 1 and then you are always incrementing only that value.
Comments
I think the array should either contain all strings or all integers.
var arr = [01, 0];
Or
var arr = ["01", "0"]
You should prefer first method for easy calculations..
"" + item.weight + item.quantity, 1comma syntax ?