Created
March 1, 2021 13:08
-
-
Save steveruizok/a47254161398e419b8e73cfccc452be0 to your computer and use it in GitHub Desktop.
Unique values in an array.
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
// Get unique values from an array of primitives | |
export function unique<T extends any>(arr: T[]) { | |
return Array.from(new Set(arr).values()) | |
} | |
export function uniqueAdjacent<T extends any>(arr: T[]) { | |
return arr.filter((t, i) => i === 0 || !(t === arr[i - 1])) | |
} | |
// Get unique values from an array of objects (or anything) | |
export function uniqueObj<T extends any>(arr: T[]) { | |
return Array.from(new Map(arr.map((p) => [JSON.stringify(p), p])).values()) | |
} | |
export function uniqueAdjacentObj<T extends any>(arr: T[]) { | |
return arr.filter( | |
(t, i) => i === 0 || !(JSON.stringify(t) === JSON.stringify(arr[i - 1])) | |
) | |
} | |
// Get unique values from an array of arrays | |
export function uniqueArr<T extends any[]>(arr: T[]) { | |
return Array.from(new Map(arr.map((p) => [p.join(), p])).values()) | |
} | |
export function uniqueAdjacentArr<T extends any[]>(arr: T[]) { | |
return arr.filter( | |
(t, i) => i === 0 || !t.every((v, j) => v === arr[i - 1][j]) | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment