Skip to content

Instantly share code, notes, and snippets.

@iffa
Last active April 16, 2021 13:11
Show Gist options
  • Save iffa/0e63fe195328e7db4aea315ad40230fb to your computer and use it in GitHub Desktop.
Save iffa/0e63fe195328e7db4aea315ad40230fb to your computer and use it in GitHub Desktop.
TypeScript function that takes an array of any type (object or primitive) and filters it distinctively, returning an array of unique values.
/**
* Takes an array of any type (object or primitive) and filters it distinctively.
* Duplicate values are removed, determined by the compare function.
*
* @param array Array to filter
* @param compare Compare function to compare objects for equality
* @returns Filtered array with distinct values
*/
export function filterDistinct<T>(
array: T[],
compare: (a: T, b: T) => boolean
): T[] {
return array.filter(
(value, index, array) =>
array.findIndex((other) => compare(value, other)) === index
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment