unique.ts 536 B

12345678910111213141516
  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 index === self.findIndex(i => {
  9. if (byKey === undefined) {
  10. return i === item;
  11. } else {
  12. return i[byKey] === item[byKey];
  13. }
  14. });
  15. });
  16. }