Reputation: 837
If I have a list like this:
var a= [['1'[0]],['2'[0]],['3'[0]],['4'[0]]];
and if condition that should another variable be equal to either '1','2','3','4' then to increment the values of their list eg:
for(var i=0; i<a; i++{
if(a[i] == z) {
a[i] += z;
}
}
I know the above code will not work, but how could I get each 'inner' element to incerment?
I'm a javascript novice, so please excuse any errors in the code.
Thanks
Upvotes: 1
Views: 115
Reputation: 270727
Those innermost arrays are at index [1]
of the first set of inner arrays, assuming your array's actual format is:
// Note the commas between the inner elements which you don't have above.
var a = [['1',[0]],['2',[0]],['3',[0]],['4',[0]]];
So you're nearly there, you need to access a[i][1][0]
and incrememnt it ++
rather than += z
.
Examples:
console.log(a[1][1][0]);
// 0 (at element '2')
// z is the string value you are searching for...
for(var i=0; i < a.length; i++) {
// Match the z search at a[i][0]
// because a[i] is the current outer array and [0] is its first element
if(a[i][0] == z) {
// Increment the inner array value which is index [i][1][0]
// Because the 1-element inner array is at [i][1] and its first element is [0]
a[i][1][0]++;
}
}
So for z = '2'
:
// Flattened for readability:
a.toString();
// "1,0,2,1,3,0,4,0"
//-------^^^
Then z = '4'
:
// This time the '4' element gets incremented
a.toString();
// "1,0,2,1,3,0,4,1"
//-------^^^-----^^^
The Array[1] 0: 1
is the incremented value for z == '4'
.
Upvotes: 2
Reputation: 1153
I'm not sure of what you're trying to accomplish, but I think it's something like this:
var lists = {
'1': [0],
'2': [0]
};
function incrementList(listKey, value) {
if (lists[listKey]) {
lists[listKey] = lists[listKey].map(function(num) {
return num + value;
});
}
}
incrementList('1', 2);
console.log(lists['1'][0]); // 2
incrementList('1', 4);
console.log(lists['1'][0]); // 6
Upvotes: 1