EN
JavaScript - extend existing array with another array
0
points
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 ]