例如下面代码中,根据 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);
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);
如果只是删除重复的字符串,可以用这个方法:
const array: string[] = ["a", "b", "a", "c", "b"];
const uniqueArray: string[] = [...new Set(array)];
console.log(uniqueArray);
也可以使用 lodash:
import _ from 'lodash';
const array: string[] = ["a", "b", "a", "c", "b"];
const uniqueArray: string[] = _.uniq(array);
console.log(uniqueArray);