How to Find Unique Values by Property in an Array of Objects in JavaScript
Let’s find the distinct values for a given property among all of the JavaScript objects in an array in this short tutorial.
JavaScript Unique Values for a Property in an Array
The ES6 object type Set
only accepts one copy of each primitive value added to it, so it’s used to find unique values in JavaScript.
However, it’s not obvious how to use Set
to find the unique values for a given property among all of the objects contained in a JavaScript array.
For example, you might have an array of orders
from which you’d like to retrieve the unique email addresses of the people who made the orders.
So, for each order
, you need to save the email
property, but you don’t want any duplicate emails to appear in the list you save.
Thankfully, Set
can easily handle this situation, as we shall see in this tutorial on finding unique property values in an array of objects.
Using Set
for Unique Object Properties
When you’re working with a Set
, you can feed arbitrary values into it, and the Set
will automatically remove any duplicates.
Let’s say you want to find all the possible values for some property among several JavaScript objects. You can use Set
to filter out duplicates by using the .add()
(Set.prototype.add()
) method to add each value to the Set
.
Here’s a code example:
Once you have a Set
, you can turn it back into an array with Array.from()
or equivalently by using the ...
spread operator with square brackets []
.
As we’ll see next, you can do this programmatically in a loop over an entire array of objects, removing all of the duplicate property values at once.