unique.ts 427 B

123456789101112131415
  1. /**
  2. * 根据指定字段对对象数组进行去重
  3. * @param arr 要去重的对象数组
  4. * @param key 去重依据的字段名
  5. * @returns 去重后的对象数组
  6. */
  7. function uniqueByField<T>(arr: T[], key: keyof T): T[] {
  8. const seen = new Map<any, T>();
  9. return arr.filter((item) => {
  10. const value = item[key];
  11. return seen.has(value) ? false : (seen.set(value, item), true);
  12. });
  13. }
  14. export { uniqueByField };