JavaScript arrays allow you to store multiple elements in a single object.
You can extend an existing array with another array in JavaScript using the array1.push(…array2) statement.
Basic Example
var a = [1, 2];
var b = [3, 4, 5];
a.push(...b);
console.log(a); // [1, 2, 3, 4, 5]
This tutorial teaches you how to extend an existing array with another array in JavaScript and when it is appropriate to use each method.
Using Array Push Method
The push() method add(s) one or more items to the end of the array and returns the new length of the array.
To extend an existing array using the push()
method,
- Invoke the
push()
method in the first array - Pass the elements of the second array by extending them using the spread operator
[...]
- The elements of the second array will be pushed into the first array
Use this method when your first array is large and the second array is small. In this case, the performance is very fast.
Code
var a = [1, 2, 3];
var b = [4, 5];
a.push(...b);
console.log(a); // [1, 2, 3, 4, 5]
Using Apply and Push Method
The apply() method calls the specified function with the given this
value.
Use the push()
method and apply()
when your browser does not support ECMAScript 6.
Code
var a = [1, 2, 3];
var b = [4, 5];
a.push.apply(a, b);
console.log(a); //[1, 2, 3, 4, 5]
Using Concat Method
The concat() method merges two or more arrays into a single array object.
- It creates a new array object instead of mutating the existing array object.
- Hence, assign the result to the first array object. This way, the second array objects are concatenated to the first object and stored in the first one.
Use this method when both of your array sizes are large.
Code
var a = [1, 2];
var b = [3, 4, 5];
a = a.concat(b);
console.log(a); //[1, 2, 3, 4, 5]
Using JQuery Merge
The jquery merge() method merges the contents of two arrays into the first array object.
Code
a = [1, 2];
b = [3, 4, 5];
$.merge(a, b);
console.log(a); // [1, 2, 3, 4, 5]
These are the different JavaScript methods to append an array to another array.