DEV Community

a2n
a2n

Posted on

Maybe you should use Set()

When working with JavaScript, it is common to deal with lists of data: user IDs, email addresses, tags, categories, product names, search results, and more. The problem is that these lists often contain duplicates.

That is where Set becomes really useful.

A Set is a built-in JavaScript object that stores unique values only. This means that if you try to add the same value more than once, JavaScript will automatically keep only one copy.

const numbers = [1, 2, 2, 3, 4, 4];

const cleanNumbers = [...new Set(numbers)];

console.log(cleanNumbers);
// [1, 2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

This small pattern is one of the simplest ways to clean data in JavaScript. Instead of writing loops, conditions, or manual checks, you can pass an array into new Set() and convert it back into an array using the spread operator.

For example, imagine you receive a list of email addresses from a form, a database, or an API:

const emails = [
  "john@example.com",
  "sarah@example.com",
  "john@example.com",
  "admin@example.com"
];

const uniqueEmails = [...new Set(emails)];
Enter fullscreen mode Exit fullscreen mode

Now uniqueEmails contains each email address only once. This can help avoid sending duplicate emails, showing repeated items in a UI, or processing the same user multiple times.

Set is also useful when checking if something already exists:

const selectedTags = new Set();

selectedTags.add("javascript");
selectedTags.add("frontend");

console.log(selectedTags.has("javascript"));
// true
Enter fullscreen mode Exit fullscreen mode

This makes Set great for features like filters, selected items, permissions, tags, or any situation where each value should appear only once.

Of course, Set is not a replacement for every array use case. Arrays are still better when order, indexes, or duplicate values matter. But when your goal is uniqueness, Set is often cleaner, shorter, and easier to read.

So next time you need to remove duplicates or make sure a collection only contains unique values, remember: maybe you should use Set()!

Top comments (0)