How to Copy Array Items into Another Array

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:

let array1 = [1, 2];
let array2 = [3, 4];
let newArray = array1.concat(array2);
console.log(newArray);

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 push() method can take multiple parameters so you can use the apply() method to pass the array to be pushed as a collection of function parameters.

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:

function pushArray(arr, arr2) {
  arr.push.apply(arr, arr2);
  console.log(arr);
}
pushArray([1,2], [3,4]);

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

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

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:

let array1 = [1, 2, 3];
let array2 = [4, 5];
array1.push(...array2);
console.log(array1);

Spread syntax let 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.

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.

Do you find this helpful?

Related articles