0
var arr = []; //is a multidimensional array. 
var barr = []; //is a temp array that is dynamically updated
var key = "key1"

arr.push(key, barr);

arr now looks like this -> [key, Array(1)]

New data comes into barr how to i push another item into the nested array for the same key?

expected output should be something like this: [key, Array(2)]

3
  • Your last sentence is unclear (for the same key?). What is the expected output? Are you confusing arrays and objects? Commented Aug 3, 2017 at 22:50
  • @andy basically im looking to achieve this: [key, Array(1) ] -> [key, Array(2)] Commented Aug 3, 2017 at 22:50
  • Well, your original code doesn't produce that result. It produces [ "key1", Array[0] ] not [ "key1", Array[1] ]. Do you just want to add something into that array? Commented Aug 3, 2017 at 22:53

2 Answers 2

2

Option #1:

You can push into the barr array:

var arr = []; //is a multidimensional array. 
var barr = []; //is a temp array that is dynamically updated
var key = "key1"

arr.push(key, barr);
console.log(arr);

barr.push('key2', 'key3');
console.log(arr);

barr is a reference to the array, and when you pushed it into your arra array you actually put there the reference, so when updating barr your reference is still there (and updated).

Option #2:

You can push into the array that is in the 2nd place of your array:

var arr = []; //is a multidimensional array. 
var barr = []; //is a temp array that is dynamically updated
var key = "key1"

arr.push(key, barr);
console.log(arr);

arr[1].push('key2', 'key3');
console.log(arr);

Sign up to request clarification or add additional context in comments.

2 Comments

splice is also an option if you know where in the array you want your new element.
boom! @Dekel thats it. I was originally trying something similar to option2. where i was going wrong was arr[1].push('key2', 'key3');
0

The way you did it the "key" is actually just another value in the array (at index 0). If you want to use a string as the key you'll have to use an object. You can set and get properties using the bracket syntax. The bracket syntax works with arrays as well, but only using integers as keys.

var obj = {};
var barr = [];
var key = "key1";
obj[key] = barr;
// barr changed
obj[key] = barr;

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.