0

I need a list of unique objects based on a specific key.

const array = [
  {"name": "Joe", "age": 42},
  {"name": "Donald", "age": 69},
  {"name": "John", "age": 42},
]

How can i get a list of unique objects selected from the list assuming i want a list of people with unique ages.

const result = [
  {"name": "Joe", "age": 42},
  {"name": "Donald", "age": 69}
]

How can this be done in a performant way, is there a better way than iterating through the elements in a foreach and adding it if it does not exist in the resulting array?

2

2 Answers 2

3

One way is to feed the array to a Map where you key them by age. That will eliminate duplicates, only retaining the last in the series of duplicates. Then extract the values again from it:

const array = [{"name": "Joe", "age": 42},{"name": "Donald", "age": 69},{"name": "John", "age": 42}];
const uniques = Array.from(new Map(array.map(o => [o.age, o])).values());
console.log(uniques);

If you want to retain the first of duplicates, then first reverse the array.

Sign up to request clarification or add additional context in comments.

Comments

0

Another option is to track seen values, here using a Set passed as a closure and checking for values using its .has() method to return a boolean to a filter() call. This will retain the first seen objects.

const array = [
  { "name": "Joe", "age": 42 },
  { "name": "Donald", "age": 69 },
  { "name": "John", "age": 42 },
]

const unique = (seen => array.filter(o => !seen.has(o.age) && seen.add(o.age)))(new Set());

console.log(unique)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.