Array A is a two dimensional array. It's made up of array X and Y. I'd like to add array Z to Array A as another item in Array A. How do I do this?
Edited to add code:
arrayA = new Array(
[1, 2, 3] //array x
[4, 5, 6] //array y
);
arrayZ = new Array(7, 8, 9);
//now, how do I add arrayZ onto the end of arrayA?
-
read the faq. post the code.zzzzBov– zzzzBov2011年11月18日 14:58:30 +00:00Commented Nov 18, 2011 at 14:58
5 Answers 5
This will add it to the end of arrayA
arrayA.push(arrayZ);
Here's a reference for push: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/push
Ok, lots of responses as to how to add items to arrays, but lets start with making your code better:
arrayA = [ //don't use new Array()
[1, 2, 3],
[4, 5, 6]
];
arrayZ = [7,8,9];
There're a few ways you can do this.
You can use the array methods unshift or push
arrayA.unshift(arrayZ) //adds z to the front of arrayA
arrayA.push(arrayZ) //adds z to the end of arrayA
You can also set the location explicitly:
arrayA[0] = arrayZ //overwrites the first element
arrayA[1] = arrayZ //overwrites the second element
arrayA[2] = arrayZ //adds a new element at 2
arrayA[arrayA.length] = arrayZ //essentially the same as using push
You can also splice the new element into the array:
arrayA.splice(1, 0, arrayZ)
1 specifies the start index of the elements being inserted/removed .0 specifies how many elements should be removed, in this case we're adding and not removing any. arrayZ is the element to insert
Comments
You could push your arrays onto Array a like so
JavaScript
var a = new Array();
var x = new Array();
var y = new Array();
var z = new Array();
a.push(x);
a.push(y);
a.push(z);
Edit: After OP edited question with code example:
var z = new Array(7, 8, 9);
var a = new Array(
[1, 2, 3],
[4, 5, 6]
);
a.push(z);
Comments
Without any code I am just assuming
arr[0] = is array X
arr[1] = is array Y
so you can use arr[2] for Y
var foo = new Array()
foo[0] = new Array() // Your x
foo[1] = new Array() // Your y
foo[2] = new Array() // Your z
Comments
On ES6 you can use the spread operator (...) as follows:
arrayA = [
[1, 2, 3],
[4, 5, 6]
];
arrayB = [7,8,9];
arrayA = [...arrayA, ...[arrayB]];