Copy array items into another array

In ECMAScript 6, you can use the Spread syntax:

let arr1 = [0, 1, 2];
let arr2 = [3, 4, 5];
arr1.push(...arr2);

console.log(arr1)

Spread syntax is available in all major browsers (that excludes IE11). For the current compatibility, see this (continuously updated) compatibility table.

However, see Jack Giffin's reply below for more comments on performance. It seems concat is still better and faster than the spread operator.


Provided your arrays are not huge (see caveat below), you can use the push() method of the array to which you wish to append values. push() can take multiple parameters so you can use its apply() method to pass the array of values to be pushed as a list of function parameters. This has the advantage over using concat() of adding elements to the array in place rather than creating a new array.

However, it seems that for large arrays (of the order of 100,000 members or more), this trick can fail. For such arrays, using a loop is a better approach. See https://stackoverflow.com/a/17368101/96100 for details.

var newArray = [];
newArray.push.apply(newArray, dataArray1);
newArray.push.apply(newArray, dataArray2);

You might want to generalize this into a function:

function pushArray(arr, arr2) {
    arr.push.apply(arr, arr2);
}

... or add it to Array's prototype:

Array.prototype.pushArray = function(arr) {
    this.push.apply(this, arr);
};

var newArray = [];
newArray.pushArray(dataArray1);
newArray.pushArray(dataArray2);

... or emulate the original push() method by allowing multiple parameters using the fact that concat(), like push(), allows multiple parameters:

Array.prototype.pushArray = function() {
    this.push.apply(this, this.concat.apply([], arguments));
};

var newArray = [];
newArray.pushArray(dataArray1, dataArray2);

Here's a loop-based version of the last example, suitable for large arrays and all major browsers, including IE <= 8:

Array.prototype.pushArray = function() {
    var toPush = this.concat.apply([], arguments);
    for (var i = 0, len = toPush.length; i < len; ++i) {
        this.push(toPush[i]);
    }
};

Use the concat function, like so:

var arrayA = [1, 2];
var arrayB = [3, 4];
var newArray = arrayA.concat(arrayB);

The value of newArray will be [1, 2, 3, 4] (arrayA and arrayB remain unchanged; concat creates and returns a new array for the result).