Search⌘ K
AI Features

Tip 16: Keep Unique Values with Set

Explore how to use the JavaScript Set object to manage collections of unique values effectively. Understand methods like add() and has(), and leverage the spread operator to convert sets back to arrays. This lesson helps you write cleaner, more efficient code by extracting unique data in one pass and prepares you to use other JavaScript collections confidently.

Set

Set is a fairly simple collection that can do only one thing, but it does it very well. Set is like a specialized array that can contain only one instance of each unique item. You’ll often want to collect values from a large array of objects, but you only need to know the unique values. There are other use cases as well, but collecting a list of distinct information from a group of objects is very, very common.

Example

In that spirit, return once again to our set of filters that you’re building. To even know what a user can filter on, you need to gather all the possible values. Recall the array of dogs that you worked with earlier.

Node.js
const dogs = [
{
name: 'max',
size: 'small',
breed: 'boston terrier',
color: 'black'
},
{
name: 'don',
size: 'large',
breed: 'labrador',
color: 'black'
},
{
name: 'shadow',
size: 'medium',
breed: 'labrador',
color: 'chocolate'
}
]

How would you get a list of all the color options? In this case, the answer is obvious, but what if the list grows into several hundred dogs? How can you be sure we get all the potential choices from golden retrievers to blue pit bulls to mottled border collies?

Accessing values in a collection

One simple way to get a collection of all the colors is to use the map() ...