Last active
October 15, 2021 03:31
-
-
Save matsuby/7b3aa72ae8af59ccf03e0af57bbe8df1 to your computer and use it in GitHub Desktop.
dens rank of array
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
/** | |
* denseRank({ | |
* array: [ | |
* {name: 'a', age: 20}, | |
* {name: 'b', age: 5}, | |
* {name: 'c', age: 20}, | |
* {name: 'd', age: 75}, | |
* {name: 'e', age: 21}, | |
* ], | |
* column: 'age', | |
* ascOrDesc: 'asc' | |
* }) | |
* => [ | |
* {name: 'b', age: 5, rank: 1}, | |
* {name: 'a', age: 20, rank: 2}, | |
* {name: 'c', age: 20, rank: 2}, | |
* {name: 'e', age: 21, rank: 3}, | |
* {name: 'd', age: 75, rank: 4}, | |
* ] | |
*/ | |
const denseRank = <T extends Record<string, unknown>>({ | |
records, | |
column, | |
ascOrDesc, | |
}: { | |
records: T[] | |
column: keyof T | |
ascOrDesc: 'asc' | 'desc' | |
}): (T & { rank: number })[] => { | |
const isAsc = ascOrDesc === 'asc' | |
return Object.entries( | |
// group by column | |
records.reduce((acc: Record<string, T[]>, r) => { | |
acc[r[column] as string] ??= [] | |
acc[r[column] as string].push(r) | |
return acc | |
}, {}) | |
) | |
.sort(([a], [b]) => { | |
return isAsc ? Number(a) - Number(b) : Number(b) - Number(a) | |
}) | |
.map(([_, group], i) => { | |
return group.map((r) => ({ | |
...r, | |
rank: i + 1, | |
})) | |
}) | |
.flat() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment