Explain Codes LogoExplain Codes Logo

How to get unique values in an array

javascript
prompt-engineering
functions
callbacks
Nikita BarsukovbyNikita Barsukov·Nov 2, 2024
TLDR

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.

//I turned one apple into five. Magic, isn't it? const uniqueArray = [...new Set([1, 2, 2, 3, 4, 4, 5])]; // [1, 2, 3, 4, 5]

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.

//Hey! Old browsers need love too. const array = [1, 2, 2, 3, 4, 4, 5]; const uniqueArray = array.filter((value, index, self) => { return self.indexOf(value) === index; });

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.

//Remember, all animals are equal, but some animals are more equal than others. function getUniqueByProperty(array, propertyName) { const unique = array .map(e => e[propertyName]) .map((e, i, final) => final.indexOf(e) === i && i) .filter(e => array[e]) .map(e => array[e]); return unique; }

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.

//The Art of War: If they are too many, reduce them. const uniqueArray = array.reduce((unique, item) => { return unique.includes(item) ? unique : [...unique, item]; }, []);

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.

//Whoa there! You're officially a JavaScript black belt now. const uniqueObjectArray = [ ...new Map(array.map(item => [JSON.stringify(item), item])).values(), ];

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.