Copy elements of an array into another array in JavaScript
This post will discuss how to copy elements of an array into another array in JavaScript.
The solution should add elements of an array to another array and should not create a new array.
1. Using Array.prototype.push() function
To append values of an array into another array, you can call the push() method of the Array object.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
var first = [1, 2, 3]; var second = [4, 5]; for (var i of second) { first.push(i); } console.log(first); /* Output: [ 1, 2, 3, 4, 5 ] */ |
2. Using Function.prototype.apply() function
Alternatively, the apply() method can be used with the push() method in the following manner. The apply() method simplify calls the push() method for elements of the specified array.
|
1 2 3 4 5 6 7 8 9 |
var first = [1, 2, 3]; var second = [4, 5]; Array.prototype.push.apply(first, second); console.log(first); /* Output: [ 1, 2, 3, 4, 5 ] */ |
3. Using Spread operator
The code can be simplified using the array spread syntax since the push() method can accept multiple parameters. Using the Spread syntax, you can expand the array expression inside the push() method, which expects zero or more arguments.
|
1 2 3 4 5 6 7 8 9 |
var first = [1, 2, 3]; var second = [4, 5]; first.push(...second); console.log(first); /* Output: [ 1, 2, 3, 4, 5 ] */ |
Note that the spread syntax is not supported with IE browser and earlier versions of Edge browser.
That’s all about copying elements of an array into another array in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)