get unique elements from an array of objects with an id in javascript

You can use the filter method and the Set object to get unique elements from an array of objects with an id. Here's an example:

index.tsx
const arr = [
  { id: 1, name: 'John' },
  { id: 2, name: 'Mary' },
  { id: 1, name: 'Jane' },
  { id: 3, name: 'Bob' },
  { id: 2, name: 'Max' }
];

const uniqueArr = Array.from(new Set(arr.map(a => a.id)))
  .map(id => {
    return arr.find(a => a.id === id)
  })

console.log(uniqueArr);
// Output: [{ id: 1, name: 'John' }, { id: 2, name: 'Mary' }, { id: 3, name: 'Bob' }]
377 chars
16 lines

In this code, we first use map to create a new array with only the id property of each object. Then, we create a Set with this new array, which automatically eliminates duplicates. We use Array.from to convert the Set back to an array. Finally, we use map again to find the original object with the corresponding id. This gives us an array with only the unique elements based on the id property.

gistlibby LogSnag