How to Merge/Combine Arrays using JavaScript?
Given two or more arrays, the task is to merge (or combine) arrays to make a single array in JavaScript. The simplest method to merge two or more arrays is by using array.concat() method.
Using Array concat() Method
The contact() method concatenates (joins) two or more arrays. It creates a new array after combining the existing arrays.
Syntax
mergedArray = array1.concat( array2 );
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const mergedArray = array1.concat( array2 );
console.log(mergedArray);
Output
[ 1, 2, 3, 4, 5, 6 ]
Please Read JavaScript Array Tutorial for complete understanding of JavaScript Array.
Using Spread Operator
The spread operator is a concise way to merge two or more arrays. The spread operator expand the elements of one or more arrays into a new array. It is introduced in ES6.
Syntax
mergedArray = [ ...array1, ...array2 ];
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const mergedArray = [...array1, ...array2];
console.log(mergedArray);
Output
[ 1, 2, 3, 4, 5, 6 ]
Using Array push() Method with Spread Operator
The array push() method adds one or more elements to the end of an array and returns the new length of the array. To add one or more array using push() method, we can use Spread Operator.
Syntax
mergedArray = array1.push( ...array2 );
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
array1.push(...array2);
console.log(array1);
Output
[ 1, 2, 3, 4, 5, 6 ]
Using for Loop
The for loop can also be used to merge arrays manually by iterating through each element and pushing them into a new array.
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const mergedArray = [];
for (let i = 0; i < array1.length; i++) {
mergedArray.push(array1[i]);
}
for (let i = 0; i < array2.length; i++) {
mergedArray.push(array2[i]);
}
console.log(mergedArray);
Output
[ 1, 2, 3, 4, 5, 6 ]