Created
May 5, 2026 22:35
-
-
Save westc/6c9acf5cdfa009e68707cb4c567343fd to your computer and use it in GitHub Desktop.
dedupe() - Takes an array and removes all of the duplicate values determined by the specified hash function. This can be used to make an array of unique values but the uniqueness should rely more on underlying values or properties.
This file contains hidden or 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
| /** | |
| * Takes an array and removes all of the duplicate values determined by the | |
| * specified hash function. | |
| * @template {any[]} T | |
| * @param {T} array | |
| * @param {(value: T[number], index: number, array: T) => any} hash | |
| * @returns {T} | |
| */ | |
| function dedupe(array, hash) { | |
| const hashedValues = new Set(); | |
| return array.filter((value, index, array) => { | |
| const hashedValue = hash(value, index, array); | |
| const keepValue = !hashedValues.has(hashedValue); | |
| if (keepValue) { | |
| hashedValues.add(hashedValue); | |
| } | |
| return keepValue; | |
| }); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment