Skip to content

Instantly share code, notes, and snippets.

@westc
Created May 5, 2026 22:35
Show Gist options
  • Select an option

  • Save westc/6c9acf5cdfa009e68707cb4c567343fd to your computer and use it in GitHub Desktop.

Select an option

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.
/**
* 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