JavaScript Concatenating Arrays


Example

Two Arrays

var array1 = [1, 2];
var array2 = [3, 4, 5];
3
var array3 = array1.concat(array2);  // returns a new array
6
var array3 = [...array1, ...array2]

Results in a new Array:

[1, 2, 3, 4, 5]

Multiple Arrays

var array1 = ["a", "b"],
    array2 = ["c", "d"],
    array3 = ["e", "f"],
    array4 = ["g", "h"];
3

Provide more Array arguments to array.concat()

var arrConc = array1.concat(array2, array3, array4);
6

Provide more arguments to []

var arrConc = [...array1, ...array2, ...array3, ...array4]

Results in a new Array:

["a", "b", "c", "d", "e", "f", "g", "h"]

Without Copying the First Array

var longArray = [1, 2, 3, 4, 5, 6, 7, 8],
    shortArray = [9, 10];
3

Provide the elements of shortArray as parameters to push using Function.prototype.apply

longArray.push.apply(longArray, shortArray);
6

Use the spread operator to pass the elements of shortArray as separate arguments to push

longArray.push(...shortArray)

The value of longArray is now:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Note that if the second array is too long (>100,000 entries), you may get a stack overflow error (because of how apply works). To be safe, you can iterate instead:

shortArray.forEach(function (elem) {
    longArray.push(elem);
});

Array and non-array values

var array = ["a", "b"];
3
var arrConc = array.concat("c", "d");
6
var arrConc = [...array, "c", "d"]

Results in a new Array:

["a", "b", "c", "d"]

You can also mix arrays with non-arrays

var arr1 = ["a","b"];
var arr2 = ["e", "f"];

var arrConc = arr1.concat("c", "d", arr2);

Results in a new Array:

["a", "b", "c", "d", "e", "f"]