Extend an existing JavaScript array with another array, without creating a new array

This tutorial will show you how to extend an existing array with another array, without creating a new array in JavaScript.

We can extend an existing array with another array in multiple ways. Below are some examples of them.

push() method

The push() method adds one or more elements to the end of an array in order they are passed and returns the updated length of the array.

We will add an array with another array with push() method that will extend the array like below.

const myArray1 = [1, 2, 3];
const myArray2 = [4, 5, 6];

myArray1.push(...myArray2);

console.log(myArray1);

In the above program, I have used the spread operator (...) to spread the elements from an array into push() method as parameters.

Output:

[ 1, 2, 3, 4, 5, 6 ]

We can also use apply()with the push method instead of the spread operator to add elements from one array to an existing array and extend the existing array.

const myArray1 = [1, 2, 3];
const myArray2 = [4, 5, 6];

myArray1.push.apply(myArray1, myArray2);

console.log(myArray1);

In the above program, I have used apply() method on the push() method and passed myArray1 as the first argument and myArray2 as the second argument. All the elements of myArray2 will be pushed into the end of myArray1.

Output:

[ 1, 2, 3, 4, 5, 6 ]

Extend an existing JavaScript array with another array’s specific elements

The push() method also can be used to add a specific element from an array to another array like below.

const myArray1 = [1, 2, 3];
const myArray2 = [4, 5, 6];

myArray1.push(myArray2[1]);

console.log(myArray1);

Output:

[ 1, 2, 3, 5 ]

Using only Spread Operator (…)

The spread operator (...) is a simple way to extend an existing array with another array by adding elements from one array to an existing array, without creating a new array.

let myArray1 = [3, 5, 7];
const myArray2 = [9, 11, 13];

myArray1 = [...myArray1, ...myArray2];

console.log(myArray1);

In the above program, I have combined the arrays using the spread operator (...), then assigned the result back to myArray1.

Output:

[ 3, 5, 7, 9, 11, 13 ]

concat() method

We can use the concat() method to add elements of the different arrays together and then we can assign that result back to the original array to extend an array.

let myArray1 = [3, 5, 7];
const myArray2 = [9, 11, 13];

myArray1 = myArray1.concat(myArray2);

console.log(myArray1);

In the above program, I have combined myArray1 and myArray2 using the concat() method and assigned the result back to myArray1.

Output:

[ 3, 5, 7, 9, 11, 13 ]

Leave a Reply

Your email address will not be published. Required fields are marked *