Created
October 14, 2021 09:12
-
-
Save matsuby/5ac8fc7a22d1e721aa60b2ede02b2477 to your computer and use it in GitHub Desktop.
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
/** | |
* rank({ | |
* 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: 4}, | |
* {name: 'd', age: 75, rank: 5}, | |
* ] | |
*/ | |
const rank = <T extends Record<string, unknown>>({ | |
records, | |
column, | |
ascOrDesc, | |
}: { | |
records: T[] | |
column: keyof T | |
ascOrDesc: 'asc' | 'desc' | |
}): (T & { rank: number })[] => { | |
const isAsc = ascOrDesc === 'asc' | |
return records | |
.map((r) => ({ | |
...r, | |
rank: | |
records.filter((_r) => | |
isAsc ? _r[column] < r[column] : _r[column] > r[column] | |
).length + 1, | |
})) | |
.sort(({ rank: a }, { rank: b }) => (isAsc ? a - b : a - b)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment