Languages
[Edit]
EN

JavaScript - copy array items into another array

0 points
Created by:
Palus-Bear
1016

In this article, we would like to show you how to copy array items into another array in JavaScript.

Quick solution:

// ONLINE-RUNNER:browser;

let array1 = ['a', 'b'];
let array2 = ['c', 'd'];

array1.push(...array2);

console.log(array1); // [ 'a', 'b', 'c', 'd' ]
console.log(array2); // [ 'c', 'd' ]

 

Alternative solution

In this example, we present an alternative solution of how to copy items from array2 into array1.

// ONLINE-RUNNER:browser;

let array1 = ['a', 'b'];
let array2 = ['c', 'd'];

array1 = array1.concat(array2);

console.log(array1); // [ 'a', 'b', 'c', 'd' ]
console.log(array2); // [ 'c', 'd' ]

Note:

If you want to add two arrays and save the result inside a new array go to this article.

See also

  1. JavaScript - add array to array

References

  1. Array.prototype.push() - JavaScript | MDN
  2. Array.prototype.concat() - JavaScript | MDN
  3. Spread syntax (...) - JavaScript | MDN
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join