Karric
Karric

Reputation: 1575

Access data issue in 2D array

I'm using a 2D array to track the occurrence of a value, but I'm having issues manipulating the second-dimension value. My syntax is definitely off, as I store an integer in the 2D, but cannot get a manipulable integer back.

var list_elm = [occur1, 0], [occur2, 0] ...;
//stuff that checks for instances
var getNum = list_elm[[list_elm.length - 1][0]]; //last array item's second part
list_elm[[list_elm.length - 1][0]] += 1; //this version produces a string "01111..."
list_elm[[list_elm.length - 1][0]] = getNum++; //this produces NaN

I'm trying to increment: list_elm[...][this one].

Upvotes: 0

Views: 36

Answers (2)

Rajshekar Reddy
Rajshekar Reddy

Reputation: 19007

You are accessing the 0 index which is a string.. you need to access the index 1. Also you have extra [ ] in the syntax. To access the 2D array you write something like array[1][0] but what you have is array[[1][0]] which is wrong

Change syntax to point to index 1 and removing extra braces

list_elm[list_elm.length - 1][1] += 1;

var getNum = list_elm[list_elm.length - 1][1];

Upvotes: 1

Yasin Yaqoobi
Yasin Yaqoobi

Reputation: 2050

You have to actually get the numeric char from your string. Doing ParseInt directly on your string will give you NAN because the first char can't be converted to a number.

You can avoid the second step if your value is '1occur'. In this case you can directly parse it as int.

var list_elm = [['occur1', 0], ['occur1', 0]];

var elm = list_elm[list_elm.length-1][0]; // get the string 'occur1'
elm = parseInt(elm.substr(elm.length-1)); // get 1 from 'occur1' and covert it to integer. 
elm++; 
console.log(elm);

Upvotes: 0

Related Questions