Languages
[Edit]
EN

JavaScript - extend existing array with another array

0 points
Created by:
Brandy-Mccabe
754

In this article, we would like to show you how to extend existing array with another array using JavaScript.

Quick solution:

// ONLINE-RUNNER:browser;

var array1 = [1, 2];
var array2 = [3, 4];

array1.push(...array2);

console.log(array1); // [ 1, 2, 3, 4 ]

Note:

push() method allows us to pass multiple arguments. Used with the spread operator we can extend the existing array with another array.

 

Alternative solution

In this example, we present an alternative solution without the spread operator (...) for older versions of web browsers.

// ONLINE-RUNNER:browser;

var array1 = [1, 2];
var array2 = [3, 4];

array1.push.apply(array1, array2);

console.log(array1); // [ 1, 2, 3, 4 ]

 

References

  1. Array.prototype.push() - JavaScript | MDN
  2. 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