Javascript: Copy an array items to another

While working with javascript arrays, there is often a requirement to copy elements of one array to another array. This article demonstrates easy ways to copy elements of one array to another array in javascript.

Table of Contents:

Copy items from array to another using concat()

Javascript’s concat() method will merge two or more arrays. The concat() method does not modify the original array but will return a new array.

Example:-

Merge the arrays [1, 4, 9] and [16, 25, 36]

Code:-

var array1 = [1, 4, 9];
var array2 = [16, 25, 36];
array1 = array1.concat(array2);
console.log(array1)

Output:-

[ 1, 4, 9, 16, 25, 36 ]

Copy items from array to another using push()

Example:-

Javascript’s push() method is used to add one or more elements to an array. This method will return the new length of the array.

Merge the arrays [1, 4, 9] and [16, 25, 36]

Code:-

var array1 = [1, 4, 9];
var array2 = [16, 25, 36];
array1.push.apply(array1, array2);
console.log(array1)

Output:-

[ 1, 4, 9, 16, 25, 36 ]

Copy items from array to another using loop and push()

Example:-

Copy the array [16, 25, 36] to another array [1, 4, 9]

Code:-

var array1 = [1, 4, 9];
var array2 = [16, 25, 36];
for (var i = 0, len = array2.length; i < len; i++) 
{
    array1.push(array2[i]);
}
console.log(array1);

Output:-

[ 1, 4, 9, 16, 25, 36 ]

Copy items from array to another using spread… operator

Javascript’s Spread syntax(…) allows an iterable such as a string or an array to be expanded at places where zero or more elements are expected.

Read More : Spread syntax(…) in javascript

Example:-

Copy the array [16, 25, 36] to another array [1, 4, 9]

Code:-

var array1 = [1, 4, 9];
var array2 = [16, 25, 36];
array1.push(...array2); // returns the new length of the calling array
console.log(array1);

Output:-

[ 1, 4, 9, 16, 25, 36 ]

Read More:

I hope this article helped you in copying the data of one array to another in javascript. Good Luck !!!

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top