#set()
#filter()
#web development
#javascript

Remove Duplicate Values from JavaScript Array

Anonymous

AnonymousJan 03, 2024

The Set object, which allows you to store unique values of any type, can be used to eliminate duplicate values from a JavaScript array. Put differently, Set will eliminate duplicates for us automatically.

Here’s an example:

// Your array with duplicates
let arrayWithDupes = [1, 2, 3, 4, 2, 3, 5, 6, 1];

// Creating a Set from the array to get unique values
let uniqueSet = new Set(arrayWithDupes);

// Converting the Set back to an array
let uniqueArray = Array.from(uniqueSet);

// Ta-da! Now uniqueArray has only unique values
console.log(uniqueArray);

Alternatively, you can use the filter() method to remove duplicates. 

const names = ["Mike", "Matt", "Nancy", "Adam", "Jenny", "Nancy", "Carl"];
let unique = names.filter((value, index, self) => {
  return self.indexOf(value) === index;
});
console.log(unique); // ["Mike", "Matt", "Nancy", "Adam", "Jenny", "Carl"]

Please be aware that large arrays are not a good fit for the filter() method. using the Set object is a better option.

Happy Coding! ❤️