...

/

Tip 16: Keep Unique Values with Set

Tip 16: Keep Unique Values with Set

In this tip, you’ll learn how to quickly pull unique items from an array with Set.

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.

Press + to interact
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() ...