unique.ts 505 B

1234567891011121314
  1. /**
  2. * @description
  3. * Returns an array with only unique values. Objects are compared by reference,
  4. * unless the `byKey` argument is supplied, in which case matching properties will
  5. * be used to check duplicates
  6. */
  7. export function unique<T>(arr: T[], byKey?: keyof T): T[] {
  8. if (byKey == null) {
  9. return Array.from(new Set(arr));
  10. } else {
  11. // Based on https://stackoverflow.com/a/58429784/772859
  12. return [...new Map(arr.map(item => [item[byKey], item])).values()];
  13. }
  14. }