Skip to content

Instantly share code, notes, and snippets.

@matsuby
Created October 14, 2021 09:12
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 matsuby/5ac8fc7a22d1e721aa60b2ede02b2477 to your computer and use it in GitHub Desktop.
Save matsuby/5ac8fc7a22d1e721aa60b2ede02b2477 to your computer and use it in GitHub Desktop.
rank of array
/**
* 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