Merge two or more arrays in JavaScript

Did you ever think about merging two arrays into one array in JavaScript that contain all the element of those arrays? Or do the same thing with more than two arrays?

Well, in this article, I am going to show you how to merge multiple arrays into one array in JavaScript with the code example. So let’s continue reading to learn how to do it…

JavaScript already has the Array concat() Method. With the concat() method we can easily merge two or more arrays. The returned array will bethe combined array of two or more.

JavaScript code to merge arrays

Now we are going to write our JS code to combine multiple arrays. Below is our code which shows how we have used the JavaScript array contact() method to combine two arrays:

var arr1 = [1, 2, 3];
var arr2 = ['a', 'b', 'c'];
var mergeArr = arr1.concat(arr2)
console.log(mergeArr); // [1, 2, 3, "a", "b", "c"];

The output of the above code is given below:

[1, 2, 3, "a", "b", "c"]

We can see that, our output contains all the elements of the two arrays that we have taken. The array is now the combination of those arrays.

Well, in our example we have just taken two arrays. But with the contact() method, you can combine more than two arrays.

Here we have taken two arrays into a variable and pass it to the contact() method. We store the final joined array in another variable.

Also, read:


Below is the syntax which shows how to merge more than two arrays using JavaScript contact() method:

array1.concat(array2, array3, array4, ..., arrayN)

So, we are able to combine multiple arrays into one in JavaScript with the help of the contact() method.

I hope you learn something from this post.

Leave a Reply

Your email address will not be published. Required fields are marked *