Categories
JavaScript Answers

How to Extend an Existing JavaScript Array With Another Array Without Creating a New Array?

Spread the love

Adding items from another array to a JavaScript array is an operation that we’ve to do a lot.

In this article, we’ll look at how to add items from an existing JavaScript array to another array.

Array.prototype.push

We can call the push method to add items to an existing array.

And we can pass in as many arguments as we want to add as many items as we want.

Therefore, we can use the spread operator to spread the items from an array in the push method to spread the array into push as arguments.

For instance, we can write:

const array1 = [1, 2, 3]
const array2 = [4, 5, 6]
array1.push(...array2)
console.log(array1)

Then array1 is [1, 2, 3, 4, 5, 6] .

We can use the spread operator since ES6.

Alternatively, we can use apply to with push to append items from one array in an existing array:

const array1 = [1, 2, 3]
const array2 = [4, 5, 6]
array1.push.apply(array1, array2)
console.log(array1)

apply takes the value of this as the first argument.

And the 2nd argument is an array of arguments for push .

Therefore array1 is the same as in the previous example at the end.

We can also write:

const array1 = [1, 2, 3]
const array2 = [4, 5, 6]
Array.prototype.push.apply(array1, array2)
console.log(array1)

to do the same thing.

Array.prototype.concat

Also, we can call concat to append items from one array in an existing array.

To do this, we write:

let array1 = [1, 2, 3]
const array2 = [4, 5, 6]
array1 = array1.concat(array2)
console.log(array1)

All the items from array2 are added to array1 .

Since concat returns a new array, we’ve to assign the returned result back to array1 .

And so we get the same result as the other examples.

Spread Operator

We can just use the spread operator to spread items from one array into another.

To use it, we write:

let array1 = [1, 2, 3]
const array2 = [4, 5, 6]
array1 = [...array1, ...array2]
console.log(array1)

We spread the items from array1 and array2 into a new array.

Then we assign that result back to array1 .

And so we get the same result as before.

Conclusion

We can use the spread operator or array methods to add array items into another array.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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