How to use groupBy and map methods In Lodash
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.
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' ]
How to Remove Duplicate Elements from an Array using Lodash ?
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.
Table of Content
- Using uniq method
- Using groupBy and map methods
- Using xor function
- Using uniqBy Method
Run the below command before running the code on your system:
npm i lodash
Contact Us