How to get unique values in an array
Extracting unique values from an array is a straightforward process in JavaScript. You can use the Set
object, which only stores unique elements, coupled with the spread syntax ...
, to convert it back into a usable array.
Alternate realities (methods) when Set
is not the hero
While Set
makes handling duplicates a breeze, there are a few scenarios when it might not be the best fit, especially when dealing with objects.
Old school method using Array.filter with indexOf
For the fossils among us clinging to old browsers, or when you want to customize how duplicates are filtered, the Array.prototype.filter()
coupled with Array.prototype.indexOf()
come in handy.
Dealing with objects through custom uniqueness function
Often, you'll find yourself dealing with arrays of objects where uniqueness should be based on a specific property.
Reductio ad unum (Reduce the Array)
Another weapon in your arsenal is the Array.prototype.reduce()
method. It's a bit more complex but gives you control over the process.
Dealing with uncooperative browsers
Modern JavaScript methods like Array.includes
might not play nice with non-ES6 browsers. What do you do? You use polyfills!
Less Trodden Paths
JSON Stringify/Parse Trick for Unique Objects
A clever trick to deal with objects is using JSON.stringify()
with Set
.
The Deep Equality Check
For deep comparison, you need a function that checks the equality of two objects' properties in a recursive manner.
Sneaky exceptions
Null values, undefined, and NaN are your best friends when it comes to crashing your programs. Make sure to account for them!
Next Level Tip
Before using Set
, it's a good practice to validate your data. Set
is only comfortable with certain types or simple structures. For complex structures, consider using the custom function approach we talked about.
Was this article helpful?