javascript how to merge arrays

JavaScript: How to Merge Arrays?

Merging arrays in JavaScript is a common use case when dealing with complex data structures or when combining data from different sources. There are several ways to merge arrays in JavaScript, and we will explore some of the most effective ones in this post.

Using the Spread Operator

The Spread operator in ES6 makes it easy to merge two or more arrays into a single array. This operator is represented by three dots (…) and can be used to expand an array into individual elements. Here's an example:


const firstArray = [1, 2, 3];
const secondArray = [4, 5, 6];

const mergedArray = [...firstArray, ...secondArray];
console.log(mergedArray); // [1, 2, 3, 4, 5, 6]

We created two arrays and then merged them using the spread operator. The resulting array contains all the elements from both arrays.

Using the concat() Method

The concat() method is another way to merge arrays in JavaScript. It creates a new array that contains the elements of the original arrays in the order they were passed in. Here's an example:


const firstArray = [1, 2, 3];
const secondArray = [4, 5, 6];

const mergedArray = firstArray.concat(secondArray);
console.log(mergedArray); // [1, 2, 3, 4, 5, 6]

We used the concat() method to merge two arrays into a new array. The resulting array contains all the elements from both arrays.

Using the push() Method

The push() method can also be used to merge two or more arrays in JavaScript. It adds elements to an array and returns the new length of the array. Here's an example:


const firstArray = [1, 2, 3];
const secondArray = [4, 5, 6];

for (let i = 0; i < secondArray.length; i++) {
  firstArray.push(secondArray[i]);
}

console.log(firstArray); // [1, 2, 3, 4, 5, 6]

We used a for loop to iterate over the second array and push each element to the first array. The resulting array contains all the elements from both arrays.

Using the splice() Method

The splice() method can also be used to merge two or more arrays in JavaScript. It is a bit more complex than the previous methods but offers more flexibility. Here's an example:


const firstArray = [1, 2, 3];
const secondArray = [4, 5, 6];

firstArray.splice(firstArray.length, 0, ...secondArray);

console.log(firstArray); // [1, 2, 3, 4, 5, 6]

We used the splice() method to insert the elements of the second array into the first array starting at the end of the first array. The resulting array contains all the elements from both arrays.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe