Explain Codes LogoExplain Codes Logo

How to get distinct values from an array of objects in JavaScript?

javascript
prompt-engineering
functions
callbacks
Alex KataevbyAlex Kataev·Sep 25, 2024
TLDR

Here's a quick sneak-peak on eliminating duplication. This utilizes ES6's reduce and findIndex methods:

const array = [{id: 1, value: 'a'}, {id: 2, value: 'b'}, {id: 1, value: 'c'}]; const unique = array.reduce((acc, cur) => { if (acc.findIndex(obj => obj.id === cur.id) === -1) { /* When the object says "Be unique", JavaScript says "No problem" */ acc.push(cur); } return acc; }, []); console.log(unique); // [{id: 1, value: 'a'}, {id: 2, value: 'b'}]

acc captures the unique entities while cur battles out the duplicates leveraging findIndex.

Ways to Conquer Duplicates

Unleashing the Power of Set and map

For simple properties, Set and map() duo becomes an unbeatable choice:

const uniqueAges = [...new Set(array.map(obj => obj.age))]; // There's no age discrimination here, every age is unique ;) console.log(uniqueAges); // [age1, age2, age3, ...]

Triumph over Complex Properties Using Map

For complex properties, Map is the superhero to rescue:

const uniqueObjects = [...new Map(array.map(item => [item.key, item])).values()]; // The 'Map' says 'Only unique objects, please!' console.log(uniqueObjects); // [object1, object2, object3, ...]

Index Checks: The Old School Technique

At times, all you need is a traditional filter with an indexOf check:

const unique = array.map(e => e.id) .filter((id, index, self) => self.indexOf(id) === index) .map(id => array.find(a => a.id = id)); /* Who knew being unique could be this simple (wink ;) */ console.log(unique); // [object1, object2, ...]

Master Techniques and Thoughts

Chain Reaction: map(), Set, filter()

By combining these methods, you're not only ensuring cleaner code, but also expressing your intent clearly:

let uniqueChain = Array.from(new Set(array.map(item => item.property))) .map(property => array.find(item => item.property === property)); /* Shoutout to all the unique properties out there! */ console.log(uniqueChain); // [unique object1, unique object2, ...]

TypeScript: Type Safety

For TypeScript users, you'd be rewarded with type safety when applying similar patterns:

const unique: Array<MyObjectType> = [...new Set(array.map(item => item.propertyKey))];

Performance Always Matters

Compared to traditional loops, these methods offer better performance, especially with large datasets.

Last One Stands: Data Integrity in Deduplication

While using the map method, it retains the last occurrence in case of conflicts, which could be a blessing or a nightmare, based on your use case.