Created
January 21, 2025 07:26
-
-
Save TrejGun/42d850c8078b3d0b9fe174bcb3bc520c to your computer and use it in GitHub Desktop.
uniqueBy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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