Remove Duplicates from an Array with Set and Map

Set and Map are built-in data structures for storing collections of values,

each with their own specific characteristics and use cases.

Both Set and Map do not allow duplicate values,

so we can use them to remove duplicates from an array by spreading the array into them:

Example

// create unique arrays with Map()
const fruitsWithDuplicates2 = [
  'Mango',
  'Cashew',
  'Barley',
  'Mango',
  'Barley',
  'Berry',
  'Cashew',
];
const uniqueFruitsWithDuplicates2 = [
  ...new Map(fruitsWithDuplicates2.map((item) => [item, true])).keys(),
];

console.log(uniqueFruitsWithDuplicates2);

Output
[ 'Mango', 'Cashew', 'Barley', 'Berry' ]

Leave a comment

Your email address will not be published. Required fields are marked *