Skip to content

Instantly share code, notes, and snippets.

@SimplGy
Last active March 16, 2019 21:53
Show Gist options
  • Save SimplGy/46fb534366c6316111dca8f47d2d1162 to your computer and use it in GitHub Desktop.
Save SimplGy/46fb534366c6316111dca8f47d2d1162 to your computer and use it in GitHub Desktop.
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}`)
.join('\n');
}
// Now we know they'll print in order:
console.log(
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