How to Remove Duplicates From an Array in JavaScript
Have you ever had trouble writing out the same filtering function for arrays again and again to remove duplicates? Did you know that you can do the same by simply combining the spread operator with a new Set
? Doesn't get any shorter than this:
Copied to clipboard! Playground
// Use the spread operator with a new Set to create
// an array containing only unique values
const food = [βπ½β, βπ½β, βπ₯β, βπβ, βπβ];
const uniqueFood = [...new Set(food)];
console.log(uniqueFood);
// Results in the following output:
[βπ½β, βπ₯β, βπβ];
Apart from using Set
s, you can also use a filter, to filter out duplicate values:
Copied to clipboard! Playground
const food = [βπ½β, βπ½β, βπ₯β, βπβ, βπβ];
const uniqueFood = food.filter((f, i) => food.indexOf(f) == i);
// Gives the same result, just like using Set
console.log(uniqueFood);
Resource:
π More Webtips
Master the Art of Frontend
- Access 100+ interactive lessons
- Unlimited access to hundreds of tutorials
- Prepare for technical interviews