uniqBy()
定義
code:ts
export const uniqBy = <T>(arr: T[], predicate: (a: T) => any = a => a): T[] => {
const seen = new Set();
return arr.filter(item => {
const key = predicate(item);
if (!seen.has(key)) {
seen.add(key);
return true;
}
return false;
});
};
code:ts
export const uniqBy = <T>(arr: T[], predicate: (a: T) => any = a => a): T[] => [
...arr
.reduce((map, item) => {
const key = item === null || item === undefined ? item : predicate(item);
map.has(key) || map.set(key, item);
return map;
}, new Map())
.values()
];