merge arrays in javascript

How to Merge Two Arrays in JavaScript

Arrays are one of the most popular data structures in JavaScript. They provide lots of different features and are used extensively by web developers. Sometimes you may need to merge two arrays in JavaScript. In this article, we will learn how to merge two arrays in JavaScript.


How to Merge Two Arrays in JavaScript

Let us say you have the following two arrays.

var array1 = [1, 2];
var array2 = [2, 3];

Let us say you want to merge these two arrays meaning include all the elements present in each array while removing duplicate elements. You can easily do this using concat function available in each array since ES5.

var array3 =  array1.concat(array2);
console.log(array3); //[1, 2, 3]

Alternatively, you can also use something called destructuring, available since ES6. But in this case, your result will contain duplicates. Here is an example, we need to prefix each array with three dots (…)

var array3 = [...array1, ...array2];
console.log(array3); //[1, 2, 2, 3]

If you wish to remove duplicates, you can create a set out of the above result, and then convert the set back into an array, as shown below.

var array3 = [...new Set([...array1 ,...array2])];
console.log(array3); //[1, 2, 3]

In this article, we have learnt a couple of simple ways to merge two arrays in JavaScript. You can use this method to merge more than 2 arrays also. Here is an example to concat 3 arrays using concat() function.

var array4 = array1.concat(array2, array3);

Here is an example to merge 3 arrays using array destructuring.

var array4 = [...array1, ...array2, ...array3];

You can also use third-party libraries like jQuery or Underscore to merge arrays.

Also read:

How to Persist Variables Through Page Reload
How to Scroll to Element Using JavaScript
How to Scroll to Element Using jQuery
How to Add Delay in JavaScript Loop
How to Use Dynamic Variable Names in JavaScript

Leave a Reply

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