22

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?
1
  • read the faq. post the code. Commented Nov 18, 2011 at 14:58

5 Answers 5

31

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

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

1 Comment

5

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

4

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

3

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

2

On ES6 you can use the spread operator (...) as follows:

arrayA = [
  [1, 2, 3],
  [4, 5, 6]
];

arrayB = [7,8,9];

arrayA = [...arrayA, ...[arrayB]];

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.