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
Mentoring

Rocket Launch Your Career

Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies:

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.