QuickSnip LogoA light blue logo with a thunderbolt in bracketsQuickSnip

Unique By Key

Filters an array of objects to only include unique objects by a specified key.

  • array
  • unique

Install

npx shadcn@latest add https://quicksnip.dev/r/unique-by-key.json

This snippet is not verified yet. Review it before use, or help verify it.

Code

const uniqueByKey = (key, arr) =>
  arr.filter((obj, index, self) => index === self.findIndex((t) => t?.[key] === obj?.[key]));

Usage

const arr = [
  { id: 1, name: 'John' },
  { id: 2, name: 'Jane' },
  { id: 1, name: 'John' }
];
uniqueByKey('id', arr); // Returns: [{ id: 1, name: 'John' }, { id: 2, name: 'Jane' }]