跳到主要内容

uniqueBy

TS JS Deno

Returns all unique values of an array, based on a provided comparator function.

Use Array.prototype.reduce() and Array.prototype.some() for an array containing only the first unique occurrence of each value, based on the comparator function, fn. The comparator function takes two arguments: the values of the two elements being compared.

typescript
const uniqueBy = (arr: any[], fn: Predicate) =>
arr.reduce((acc, v) => {
if (!acc.some((x: any) => fn(v, x))) acc.push(v);
return acc;
}, []);
typescript
uniqueBy(
[
{ id: 0, value: "a" },
{ id: 1, value: "b" },
{ id: 2, value: "c" },
{ id: 1, value: "d" },
{ id: 0, value: "e" },
],
(a: any, b: any) => a.id == b.id
); // [ { id: 0, value: 'a' }, { id: 1, value: 'b' }, { id: 2, value: 'c' } ]