3 Ways To Merge Arrays In JavaScript

Introduction

Arrays are an essential data structure in JavaScript that allows us to store multiple values in a single variable. Sometimes, we may need to combine two or more arrays to perform a specific operation or manipulate data. This article will discuss various methods to combine two or more arrays in JavaScript.

Find a detailed article about Array in JavaScript,

1. Using the concat Method

The concat() method in JavaScript allows us to merge two or more arrays into a new array. This method does not modify the original arrays but creates a new array containing the original arrays' elements.

Here's an example:

let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
let arr3 = [7, 8, 9];
let mergedArr = arr1.concat(arr2, arr3);
console.log(mergedArr); // Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]

In the above example, we have used the concat() method to combine three arrays (arr1, arr2, and arr3) into a new array (mergedArr). We passed all the arrays as arguments to the concat() method, which returned a new array containing all the elements of the original arrays.

2. Using the Spread Operator

The spread operator (…) is a new feature introduced in ECMAScript 6 that allows us to expand an array into individual elements. We can use the spread operator to combine two or more arrays into a new array.

Here's an example:

let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
let arr3 = [7, 8, 9];
let mergedArr = [...arr1, ...arr2, ...arr3];
console.log(mergedArr); // Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]

In the above example, we have used the spread operator to combine three arrays (arr1, arr2, and arr3) into a new array (mergedArr). We have expanded each array using the spread operator and passed them as arguments to a new array.

3. Using the push Method

The push() method in JavaScript allows us to add one or more elements to the end of an array. We can use the push() method to add all the elements of one array to another.

Here's an example:

let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
arr1.push(...arr2);
console.log(arr1); // Output: [1, 2, 3, 4, 5, 6]

In the above example, we have used the push() method to add all the elements of arr2 to arr1. We have used the spread operator to expand the arr2 array and passed it as arguments to the push() method.

And that's it! I hope you enjoyed this post. If you've any queries or feedback, feel free to comment.