W3docs

How to Copy Array Items into Another Array

Read this JavaScript tutorial and learn several useful methods of copying array items into another array. Get to know which method to choose for your case.

There are multiple methods used to copy array items into another array. Each of them has peculiarities which we are going to discuss in this snippet.

The concat() Method

The first method is the concat function:

Javascript arrays concat method

javascript— editable

The concat method creates and returns a new array including the values from other arrays, and additional items as well.

The push() Method

If your arrays are not huge, you can use the push() method of the array to which you want to add values.

The <kbd class="highlighted">push()</kbd> method can take multiple parameters so you can use the <kbd class="highlighted">apply()</kbd> method to pass the array to be pushed as a collection of function parameters.

Javascript arrays push method

let newArray = [];
newArray.push.apply(newArray, dataArr1);
newArray.push.apply(newArray, dataArr2);

In the case of large arrays, this method may fail. Using a loop in such cases is very much recommended.

To generalize this into a function, do the following:

How to Copy Array Items into Another Array

javascript— editable

You can also add it to Array's prototype like this:

Javascript arrays push method

Array.prototype.pushArray = function (arr) {
  this.push.apply(this, arr);
};
let newArray = [];
newArray.pushArray(dataArray1);
newArray.pushArray(dataArray2);

Note: Modifying built-in prototypes like Array.prototype is generally discouraged in modern JavaScript, as it can cause naming conflicts or unexpected behavior with other libraries.

This method has the advantage over the concat method of adding elements to the array in place, not creating a new array.

The Spread Syntax

You can use the Spread Syntax which will simplify the code:

Javascript arrays spread syntax

javascript— editable

Spread syntax allows an iterable (array expression, string) be expanded in places where zero or more arguments/elements are expected, or object expression be expanded in places where zero or more key-value pairs are expected.

Note: All the methods above perform a shallow copy. If your arrays contain objects, only the references are copied, not the objects themselves.

Arrays

The JavaScript arrays are high-level and list-like objects that can be used for storing several values in a single variable. An array is a unique variable that is capable of holding multiple values at the same time. Arrays start at zero index and can be manipulated with different methods.