0

I am trying to push values into a multidimensional array and read values out of it based on code that i've seen on other posts on this site. This is my array push code.

SelectedWindowGraphs.push([ContainerIDValue,elementID+"chkbox"]);

ContainerIDValue is an integer and elementID+"chkbox" is what i want to store at that position in the array. Here is what i saw when i debugged my code:

enter image description here

This is not what i want. At position 0, i want CUT17chkbox, CUT18chkbox, and CUT19chkbox. How do i fix my array so that i does that?

0

3 Answers 3

1
// initialize an array at that position in case it has not been defined yet
SelectedWindowGraphs[ContainerIDValue] = (SelectedWindowGraphs[ContainerIDValue] || 
[]); 
// push the value at the desired position
SelectedWindowGraphs[ContainerIDValue].push(elementID+"chkbox"); 
Sign up to request clarification or add additional context in comments.

Comments

1

You have to push to a subarray:

 if(!SelectedWindowGraphs[ContainerIDValue])
   SelectedWindowGraphs[ContainerIDValue] = [];

 SelectedWindowGraphs[ContainerIDValue]
  .push(elementID+"chkbox");

Comments

0

You could add elements at certain position just doing:

var arr = [ 1, 2, 3, 4, 5, 6, 7 ]

arr[2] = "three";

console.log(arr);//[ 1, 2, 'three', 4, 5, 6, 7 ]

In a multidimensional array:

var arr = [ 1, [2, 3, 4, 5, 6], 7 ]

arr[1][2] = "four";

console.log(arr);//[ 1, [ 2, 3, 'four', 5, 6 ], 7 ]

When you perform push you are adding one or more elements at the end.

var arr = [1,2,3]

arr.push(4,5);//you are adding 4 and then 5

console.log(arr);//[ 1, 2, 3, 4, 5 ]

In a multidimensional array:

var arr = [1,2,[3,4]]

arr[2].push(5,6);//position 2

console.log(arr);//[ 1, 2, [ 3, 4, 5, 6 ] ]

To insert an element in a specific position (and move right element n positions) you could use splice(). In the following case, 2th and 3th position

var arr = [ 1, 2, 3, 4, 5 ]

arr.splice(2, 0, 999, 8888);

console.log(arr);//[ 1, 999, 8888, 2, 3, 4, 5 ]

In a multidimensional array:

var arr = [ 1, 2, [3,4,5], 6, 7 ]

arr.splice(2, 0, [8,9,10]);

console.log(arr);//[ 1, 2, [ 8, 9, 10 ], [ 3, 4, 5 ], 6, 7 ]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.