unique.ts 596 B

12345678910111213141516171819
  1. /**
  2. * Returns an array with only unique values. Objects are compared by reference,
  3. * unless the `byKey` argument is supplied, in which case matching properties will
  4. * be used to check duplicates
  5. */
  6. export function unique<T>(arr: T[], byKey?: keyof T): T[] {
  7. return arr.filter((item, index, self) => {
  8. return (
  9. index ===
  10. self.findIndex(i => {
  11. if (byKey === undefined) {
  12. return i === item;
  13. } else {
  14. return i[byKey] === item[byKey];
  15. }
  16. })
  17. );
  18. });
  19. }