首页  编辑  

从数组中,删除重复的对象(根据对象的特定属性判定是否重复)

Tags: /Node & JS/   Date Created:
例如下面代码中,根据 Demo.id 或者 User.username 来删除数组中重复的元素。
function removeDuplicates<T, K extends keyof T>(array: T[], key: K): T[] {
  const seen = new Set<T[K]>();
  return array.filter(item => {
    const duplicate = seen.has(item[key]);
    seen.add(item[key]);
    return !duplicate;
  });
}

interface Demo {
  id: number;
  name: string;
}

let demos: Demo[] = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
  { id: 1, name: 'Alice' },
  { id: 3, name: 'Charlie' }
];

let uniqueDemos = removeDuplicates<Demo, keyof Demo>(demos, 'id');

console.log(uniqueDemos);
// 输出: [
//   { id: 1, name: 'Alice' },
//   { id: 2, name: 'Bob' },
//   { id: 3, name: 'Charlie' }
// ]

interface User {
  username: string;
  email: string;
}

let users: User[] = [
  { username: 'alice', email: 'alice@example.com' },
  { username: 'bob', email: 'bob@example.com' },
  { username: 'alice', email: 'alice2@example.com' },
  { username: 'charlie', email: 'charlie@example.com' }
];

let uniqueUsersByUsername = removeDuplicates<User, keyof User>(users, 'username');

console.log(uniqueUsersByUsername);
// 输出: [
//   { username: 'alice', email: 'alice@example.com' },
//   { username: 'bob', email: 'bob@example.com' },
//   { username: 'charlie', email: 'charlie@example.com' }
// ]
如果只是删除重复的字符串,可以用这个方法:
const array: string[] = ["a", "b", "a", "c", "b"];
const uniqueArray: string[] = [...new Set(array)];
console.log(uniqueArray); // 输出: ["a", "b", "c"]
也可以使用 lodash:
import _ from 'lodash';

const array: string[] = ["a", "b", "a", "c", "b"];
const uniqueArray: string[] = _.uniq(array);
console.log(uniqueArray); // 输出: ["a", "b", "c"]