Open In App

Extend existing JS array with Another Array

Last Updated : 15 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

To extend an array with another without creating a new array we can use the JavaScript array.push() method. This method extend the array by adding the elements at the end. These are the following methods:

1. Using array.push() with Spread operator

JavaScript array.push() method adds one or more elements to the end of an array and returns the new length of the array. Spread Operator expands an iterable into individual elements.

JavaScript
const a1 = [ 10, 20, 30 ]
const a2 = [ 40, 50 ]

// Extend the array using array.push()
a1.push(...a2);

console.log(a1);

Output
[ 10, 20, 30, 40, 50 ]

2. Using Array push.apply() Method

Array push.apply() method is used when the ES6 is not supported. It is used to add elements at the end of the array.

JavaScript
const a1 = [ 10, 20, 30 ]
const a2 = [ 40, 50 ]
// Extend the array using array.push.apply()
a1.push.apply( a1, a2 );
console.log(a1);

Output
[ 10, 20, 30, 40, 50 ]

3. Using Spread Operator

The spread operator is used to expand the individual elements from the array and these elements can be converter to array using the aray literals.

JavaScript
let a1 = [ 10, 20, 30 ]
let a2 = [ 40, 50 ]
a1 = [ ...a1, ...a2 ];
console.log(a1);

Output
Updated first array: [ 10, 20, 30, 40, 50 ]

4. Using array.splice() Method

The array.splice() method is used to remove, replace and add one or more elements in the existing array.

JavaScript
let a1 = [ 10, 20, 30 ]
let a2 = [ 40, 50 ]

// Extend existing array using splice()
a1.splice( a1.length, 0, ...a2);

console.log(a1);

Output
[ 10, 20, 30, 40, 50 ]


Next Article
Article Tags :

Similar Reads