0
0
JavascriptHow-ToBeginner · 3 min read

How to Get Unique Values from Array of Objects in JavaScript

To get unique values from an array of objects in JavaScript, use Array.map() to extract the property values, then use new Set() to remove duplicates, and finally convert it back to an array with Array.from() or spread syntax. This method efficiently filters unique values based on a specific object property.
📐

Syntax

Use Array.map() to create an array of values from the objects, then wrap it with new Set() to remove duplicates. Convert the Set back to an array using Array.from() or spread syntax [...set].

  • array.map(obj => obj.property): extracts values of a property
  • new Set(array): creates a set of unique values
  • Array.from(set) or [...set]: converts set back to array
javascript
const uniqueValues = Array.from(new Set(array.map(obj => obj.property)));
💻

Example

This example shows how to get unique names from an array of user objects.

javascript
const users = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
  { id: 3, name: 'Alice' },
  { id: 4, name: 'Charlie' }
];

const uniqueNames = [...new Set(users.map(user => user.name))];
console.log(uniqueNames);
Output
["Alice", "Bob", "Charlie"]
⚠️

Common Pitfalls

One common mistake is trying to use Set directly on the array of objects, which won't work because objects are compared by reference, not by value. Another pitfall is forgetting to extract the property before creating the set, which results in no duplicates being removed.

javascript
const users = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
  { id: 3, name: 'Alice' }
];

// Wrong: Set on objects (no duplicates removed)
const wrong = [...new Set(users)];
console.log(wrong);

// Right: Extract property first
const right = [...new Set(users.map(user => user.name))];
console.log(right);
Output
[{"id":1,"name":"Alice"},{"id":2,"name":"Bob"},{"id":3,"name":"Alice"}] ["Alice","Bob"]
📊

Quick Reference

  • Use map() to get values from objects.
  • Use Set to remove duplicates.
  • Convert Set back to array with Array.from() or spread [...set].
  • Objects need property extraction before uniqueness check.

Key Takeaways

Extract the property values first using Array.map before removing duplicates.
Use new Set() to filter unique values efficiently.
Convert the Set back to an array with Array.from() or spread syntax.
Do not use Set directly on objects to find unique objects by value.
This method works well for primitive property values like strings or numbers.