How to extend an existing array with another array without creating a new array in JavaScript ?
Last Updated :
10 Mar, 2023
JavaScript arrays are a powerful data structure that allows you to store and manipulate collections of data. Often, we may need to combine or extend two or more arrays into a single array. It’s easy to create a new array by concatenating two or more arrays but if we want to extend an existing array without creating a new array.
There are two easy ways to do this in JavaScript.
Using the ‘push()’ method
Using spread operator(‘…’ )
The following shows how you can use the ‘push()’ method to add the elements of one array to another array.
Syntax:
arr1.push(...arr2);
Example 1: In this example, we have two arrays ‘arr1’ and ‘arr2’. We use the ‘push()’ method on ‘arr1’ and spread ‘arr2’ using the spread operator (‘…’) . This appends the elements of ‘arr2’ to ‘arr1’ without creating a new array.
Javascript
<script>
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
arr1.push(...arr2);
console.log(arr1);
</script>
Output:
[1, 2, 3, 4, 5, 6 ]
Alternatively, you can use the spread operator to create a new array with the elements of both arrays, and then assign the new array back to the original array to extend it.
Syntax:
arr1 = [...arr1, ...arr2];
Example 2: It’s important to note that extending an array in place can be a destructive operation since it modifies the original array. If you need to keep the original array intact, consider creating a new array with the elements of both arrays using the spread operator, as shown in the second example.
Javascript
<script>
let arr1 = ['geeks', 'for']
let arr2 = ['geeks']
arr1 = [...arr1, ...arr2]
console.log(arr1);
</script>
Output:
[ 'geeks', 'for', 'geeks' ]
Share your thoughts in the comments
Add Your Comment
Please Login to comment...