Sign Up
Go Pro Sign Up Login

How to Get Unique Values From an Array or Collection

Apr 23, 2021

Scott Tolinski

tldr; Use Sets and spread results

From an array

const unique = [...new Set(["one", "two", "one"])]
// ["one", "two"]

From a collection

const unique = [...new Set([{
  value: "one",
},{
  value: "two",
},{
  value: "one",
}].map((obj) => obj.value))]
// ["one", "two"]

Why does this work?

Let's break down what we're doing here.

What is a Set?

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set

"The Set object lets you store unique values of any type, whether primitive values or object references."

That's really it. By definition a JavaScript set is a collection of values that may only exist once. As of ES2015, this comparison is done by the same algorithm as "===".

Why Spread?

[...set]

This creates a new array out of the values created in the set. This is essentially just converting the set back to an array. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set#iterating_sets

Put it all together and you have

const unique = [...new Set(["one", "two", "one"])]

What about a collection

A collection is just an array of objects. In the initial example shown, we're just doing a map over that collection to pull out the specific values from the collection and put them into an array, which is then converted to a Set and back to an array. That conversion is what gives us our unique values.