How to Remove Duplicates From an Array in JavaScript

How to Remove Duplicates From an Array in JavaScript

Ferenc Almasi β€’ 2020 July 30 β€’ Read time 1 min read
  • twitter
  • facebook
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:
[β€˜πŸŒ½β€™, β€˜πŸ₯”’, β€˜πŸ†β€™];
unique.js

Apart from using Sets, 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);
filter.js
Remove duplicates from an array in JavaScript
If you would like to see more Webtips, follow @flowforfrank

Resource:

  • twitter
  • facebook
JavaScript
Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Access 100+ interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Prepare for technical interviews
Become a Pro

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.