unique.ts 549 B

12345678910111213141516
  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. import { isObject } from './shared-utils';
  8. export function unique<T>(arr: T[], byKey?: keyof T): T[] {
  9. if (byKey == null) {
  10. return Array.from(new Set(arr));
  11. } else {
  12. // Based on https://stackoverflow.com/a/58429784/772859
  13. return [...new Map(arr.map(item => [item[byKey], item])).values()];
  14. }
  15. }