Lodash - merge two arrays and remove duplicates from it

If you are using Lodash library in your project then merging multiple arrays and remove duplicate values from it is very easy. We will ne using the union() function of lodash to perform this task.

const arr1 = [10, 20, 30, 40];
const arr2 = [20, 30, 50, 60, 70];
const arr3 = [50, 70, 80, 90, 100];

const result = _.union(arr1, arr2, arr3);




Try it yourself

We are using the lodash library _.union() function to merge multiple arrays into one and remove duplicate items from it. Lodash is a javascript library to make arrays and objects manipulations easy.

Code Example Explanation

1. We have created three arrays here arr1, arr2, arr3 that contain integer type values. 

2. We are passing all the above arrays inside the _.union() function as parameters.

3. The union() function is returning us a new array that is created with the concatenation of the above arrays and it will not have any duplicate value.

# Code example 2: merge and remove duplicates from string type values arrays.

const arr1 = ["John", "Samual", "Rock", "Phabha"];
const arr2 = ["Samual", "Carl", "John", "Natasha"]

const result = _.union(arr1, arr2);




Try it yourself

Was this helpful?