DEV Community

Cover image for How to merge two arrays and remove duplicates from the array in JavaScript?
MELVIN GEORGE
MELVIN GEORGE

Posted on • Originally published at melvingeorge.me

How to merge two arrays and remove duplicates from the array in JavaScript?

Originally posted here!

Jump to the full solution →

Step 1: Merge two arrays

To merge 2 arrays in JavaScript, we can use the concat() array method.

Consider this 2 arrays with some numbers repeated on both of the arrays,

// arrays
const arr1 = [1, 2, 3, 4, 5];
const arr2 = [3, 4, 5, 6, 7];
Enter fullscreen mode Exit fullscreen mode

First let's merge this array using the concat() method in the arr1 array like this,

// arrays
const arr1 = [1, 2, 3, 4, 5];
const arr2 = [3, 4, 5, 6, 7];

// merge arrays
// using the concat() method
// concat() method returns a new array
const arr3 = arr1.concat(arr2);

console.log(arr3); // [1, 2, 3, 4, 5, 3, 4, 5, 6, 7]
Enter fullscreen mode Exit fullscreen mode
  • The concat() method returns a new array after merging.

Step 2: Remove Duplicate elements from an array

As you can see that after merging the arrays we have duplicate elements in our new array.

Now let's use the Set() constructor function to remove duplicate or repeated elements.

So let's pass the new array arr3 as an argument to the function like this,

// arrays
const arr1 = [1, 2, 3, 4, 5];
const arr2 = [3, 4, 5, 6, 7];

// merge arrays
// using the concat() method
// concat() method returns a new array
const arr3 = arr1.concat(arr2);

const uniqueElements = new Set(arr3);
Enter fullscreen mode Exit fullscreen mode

Now, all we have to do is use the spread operator (...) to extract the unique elements from the Set collection into a new array.

It can be done like this,

// arrays
const arr1 = [1, 2, 3, 4, 5];
const arr2 = [3, 4, 5, 6, 7];

// merge arrays
// using the concat() method
// concat() method returns a new array
const arr3 = arr1.concat(arr2);

// use Set() constructor function
// to remove duplicate or repaeted elements
const uniqueElements = new Set(arr3);

// use the spread operator ...
// to extract values from Set collection
// to an array
const uniqueValArr = [...uniqueElements];

console.log(uniqueValArr); // [1, 2, 3, 4, 5, 6, 7]
Enter fullscreen mode Exit fullscreen mode

Yay! We have successfully merged our 2 arrays and removed the duplicate elements from the array. 😃

The above code can be further reduced like this,

// arrays
const arr1 = [1, 2, 3, 4, 5];
const arr2 = [3, 4, 5, 6, 7];

// merge arrays
// using the concat() method
// and use the Set() constructor function to get unique values
// and use the spread operator to extract unique values to an array
const uniqueValArr = [...new Set(arr1.concat(arr2))];

console.log(uniqueValArr); // [1, 2, 3, 4, 5, 6, 7]
Enter fullscreen mode Exit fullscreen mode

See this example live in JSBin.

Feel free to share if you found this useful 😃.


Top comments (0)