Merge Two Arrays and Remove Duplicates – JavaScript

An array is an ordered list of values and these values can be of any data type. Eg integer, string, boolean value or it can be a mix of all types.

Merging arrays is one of the common tasks and very easy to accomplish in JavaScript using inbuilt functions like spread operator (...) and concat() .

However, while merging two or more arrays, we may come across duplicate items in the array.

Example : If we just merge [1,2,3,4] and [1,2,5,6] we will get [1, 2, 3, 4, 1, 2, 5, 6] . Here 1 and 2 are the duplicate items in the array.

So here in this article, we will see how to merge and remove duplicates from an array in JavaScript.

Using Set and Spread Operator (…) to remove duplicates from array

The Spread Operator (...) can be used for adding items to arrays or for combining arrays or objects. It allows elements from an array or objects to be included in a list of some form.

The Set() in JavaScript is described as a collection of unique values. This means a value can occur only once in a Set. And a Set can store values of any data type.

Example:

const arr1 = [1,2,3,4]
const arr2 = [1,2,5,6]

const mergeArr = [...arr1, ...arr2] // merge array but don't remove duplication

console.log([...new Set(mergeArr)]) // remove duplicates from the array

Output:

[1, 2, 3, 4, 5, 6]

Using Set and concat() function to merge and remove duplicates in array

The concat() method is used to combine elements of two or more arrays in JavaScript. It does not modify the original arrays.

Here in the example, we will use concat() method to combine two arrays, and then we will use the spread operator (...) and create a new Set() to remove all the duplicate items from the array.

REMINDER: Set is a collection of unique values only. Same value cannot occur twice.

Example :

const arr1 = [1,2,3,4]
const arr2 = [1,2,5,6]
const mergeArr = [].concat(arr1,arr2) //Merge two array 
const removeDup = [...new Set(mergeArr)] // Remove duplicate from the array

console.log(removeDup)

Output:

[ 1, 2, 3, 4, 5, 6 ]

Using Underscore.js or Lo-Dash to remove duplicates in array JavaScript

Underscore.js or LoDash are utility library in JavaScript that have some pre-made functions that help us to perform some common task in JavaScript with just one function.

For example, to merge and remove the duplicate items from the array we just have to use _.union() function.

Example:

const arr1 = [1,2,3,4]
const arr2 = [1,2,5,6]
const arr3 = [2,1]

console.log(_.union(arr1, arr2, arr3));

Output:

[ 1, 2, 3, 4, 5, 6 ]

Related Topics:

Remove First And Last Element From An Array In JavaScript

Scroll to Top