How to Merge Two Arrays Without Creating a New Array in JavaScript?
Given two arrays, the task is to merge both arrays to make a single array without creating a new array in JavaScript. It modifies one array in place to store the merged array elements.
We can use the array push() method to insert array elements into another array using Spread Operator. This approach will modify the first array in place and won't create a new array.
Syntax
array1.push( ...array2);
let array1 = [ 1, 2, 3 ];
let array2 = [ 4, 5, 6 ];
array1.push(...array2);
console.log(array1);
Output
[ 1, 2, 3, 4, 5, 6 ]
Please Read JavaScript Array Tutorial for complete understanding of JavaScript Array.
Using Array concat() Method
We can use array concat() method to Merge Two Arrays Without Creating a New Array. It is a very basic method to merge arrays. It takes second array as a parameter and store the merged array to the first array.
Syntax
array1 = array1.concat( array2 );
let array1 = [ 1, 2, 3 ];
let array2 = [ 4, 5, 6 ];
// Store the merged array to first array
array1 = array1.concat(array2);
console.log(array1);
Output
[ 1, 2, 3, 4, 5, 6 ]
Using Array splice() Method
The array splice() method is used to modify the contents of an array by removing the existing elements and/or by adding new elements.
Syntax
array1.splice( index, removeCount, ...array2 )
let array1 = [ 1, 2, 3 ];
let array2 = [ 4, 5, 6 ];
array1.splice(array1.length, 0, ...array2);
console.log(array1);
Output
[ 1, 2, 3, 4, 5, 6 ]
Using a for Loop
We can also use for loop to merge two arrays without creating a new array. We will use for loop with push() method to merge arrays without creating new array.
let array1 = [ 1, 2, 3 ];
let array2 = [ 4, 5, 6 ];
for (let i = 0; i < array2.length; i++) {
array1.push(array2[i]);
}
console.log(array1);
Output
[ 1, 2, 3, 4, 5, 6 ]