Append array to array

Append array to array
0

#1

Can’t seem to find the answer to this, but I’m trying to use push to add an array on the end of another, not insert it. So

myArray.push(otherArray);

gives me something like

[“a”,“b”,[“c”,“d”]]

but what I’m trying to get is

[“a”,“b”][“c”,“d”]

Help is greatly appreciated!


#3

Concat seems to just put it all together, so

var tryConcat = myArray.concat(otherArray);

returns [“a”,“b”,“c”,“d”]


#4

I may be wrong but I guess this will only happen if you have an empty array, and you push both of these arrays into that empty array. For example:

var emptyArray=[];
emptyarray.push(myArray);
emptyarray.push(otherarray);

#5

That worked, thank you!


#6

Glad I could help :slight_smile:


#7

There is a great feature for this in ES6 called the spread operator. You use with with three dots.

Say you have three arrays you want to join into a new array:

arr1 = [ ‘a’, ‘b’, ‘c’ ];
arr2 = [ ‘d’, ‘e’, ‘f’ ];
arr3 = [ ‘g’, ‘h’, i ];

arr4 = [ …arr1, …arr2, …arr3 ];

results: [ ‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’, ‘h’, ‘i’ ];

See:
Array Spread documentation on MDN.

Oh, on review, I see you may have simply wanted an array of two arrays, in that case you can Array literal syntax and simply:

arr3 = [ arr1, arr2 ];