Last active
April 16, 2021 13:11
-
-
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.
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
/** | |
* 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