Skip to content

Instantly share code, notes, and snippets.

@aaronbeall
Created March 13, 2018 15:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aaronbeall/009888ac96f0de236140399c8f993294 to your computer and use it in GitHub Desktop.
Save aaronbeall/009888ac96f0de236140399c8f993294 to your computer and use it in GitHub Desktop.
function uniqueArray<T>(array: T[], toUniqueValue?: (current: T) => any): T[] {
const values = toUniqueValue ? array.map(toUniqueValue) : array;
return array.filter((current, index) => values.indexOf(values[index]) == index);
}
// Example
const array = [{ id: 0, k: "a" }, { id: 1, k: "b" }, { id: 2, k: "a" }, { id: 3, k: "c" }];
const result = uniqueArray(array, item => item.k);
expect(result).toEqual([{ id: 0, k: "a" }, { id: 1, k: "b" }, { id: 3, k: "c" }]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment