Skip to content

Instantly share code, notes, and snippets.

@TrejGun
Created January 21, 2025 07:26
Show Gist options
  • Save TrejGun/42d850c8078b3d0b9fe174bcb3bc520c to your computer and use it in GitHub Desktop.
Save TrejGun/42d850c8078b3d0b9fe174bcb3bc520c to your computer and use it in GitHub Desktop.
uniqueBy
export const uniqueBy = <T extends Record<string, any> = Record<string, any>>(
array: T[],
by: string | string[],
): T[] => {
const uniqueArray: T[] = [];
array.forEach(item => {
const found = uniqueArray.find(it => {
if (Array.isArray(by)) {
return by.every(b => it[b] === item[b]);
}
return it[by] === item[by];
});
if (!found) {
uniqueArray.push(item);
}
});
return uniqueArray;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment