Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
sort keys of an object using an array index as rank, with TypeScript
export interface SomeShape {
b: string,
c: string,
a: string,
// Specify your sort order here
const rank: Array<keyof SomeShape> = ['a', 'b', 'c'];
export function sortedKvpString(obj: SomeShape) {
return Object.entries(obj)
.sort(([a_], [b_]) => {
const a = a_ as keyof SomeShape; // #ts workaround :.(
const b = b_ as keyof SomeShape;
return rank.indexOf(a) - rank.indexOf(b);
.map(([key, val])=> `* ${key}: ${val}`)
// Now we know they'll print in order:
sortedKvpString({b: 3, a: 1, c: 5}) // prints a,b,c
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment