Open In App

How to Remove Duplicate Elements from an Array using Lodash ?

Last Updated : 23 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Removing duplicate elements from an array is necessary for data integrity and efficient processing. The approaches implemented and explained below will use the Lodash to remove duplicate elements from an array.

Run the below command before running the code on your system:

npm i lodash

Using uniq method

In this approach, we will use Lodash’s uniq function, which returns a new array with unique elements from the input array, removing duplicates while maintaining the order of elements.

Syntax:

_.uniq(array)

Example: The below example uses the uniq function to remove duplicate elements from an array using Lodash.

JavaScript
const _ = require('lodash');
let arr = 
    ["apple", "mango", "apple", 
    "orange", "mango", "mango"];
let res = _.uniq(arr);
console.log(res);

Output:

[ 'apple', 'mango', 'orange' ]

Using groupBy and map methods

In this approach, we will use the Lodash’s groupBy function to group the elements of the array based on their values, and then using the Lodash’s map to extract the unique keys (values) from the grouped object, removing duplicates while preserving the order of elements.

Syntax:

let grouped = _.groupBy(array), 
let uniqueArr = _.map(grouped, (value, key) => key);

Example: The below example uses groupBy and map functions to remove duplicate elements from an array using Lodash.

JavaScript
const _ = require('lodash');
let arr = 
    ["apple", "mango", "apple", 
    "orange", "mango", "mango"];
let grouped = _.groupBy(arr);
let res = _.map(grouped, 
    (value, key) => key);
console.log(res);

Output:

[ 'apple', 'mango', 'orange' ]

Using xor function

In this approach, we are using the xor function of Lodash with an empty array as the second argument to create a new array containing unique elements from the input array arr, removing duplicates.

Syntax:

_.xor([arrays])

Example: The below example uses the xor function to remove duplicate elements from an array using Lodash.

JavaScript
const _ = require('lodash');
let arr = 
    ["apple", "mango", "apple", 
    "orange", "mango", "mango"];
let res = _.xor(arr, []);
console.log(res);

Output:

[ 'apple', 'mango', 'orange' ]

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads