Append array to array

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!

Concat seems to just put it all together, so

var tryConcat = myArray.concat(otherArray);

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

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);
2 Likes

That worked, thank you!

1 Like

Glad I could help :slight_smile:

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 ];

2 Likes