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 one array to another using concat()
- Copy items from one array to another using push()
- Copy items from one array to another using loop and push()
- Copy items from one array to another using spread operator
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:-
Frequently Asked:
- Javascript Sort Array of Integers
- Loop through an array in javascript (6 ways)
- Javascript: Get loop counter/ index in loop
- Javascript: Copy an array items to another
[ 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:
- Javascript: Insert an item to array at specific index
- Javascript: Check if an array is empty
- Javascript: Convert array to string (4 ways)
I hope this article helped you in copying the data of one array to another in javascript. Good Luck !!!