Skip to content

Instantly share code, notes, and snippets.

@stevenliebregt
Created May 19, 2022 11:23
Show Gist options
  • Save stevenliebregt/f8e6ea42262a9a25b4ddd3b60fd72a7d to your computer and use it in GitHub Desktop.
Save stevenliebregt/f8e6ea42262a9a25b4ddd3b60fd72a7d to your computer and use it in GitHub Desktop.
Sort a list of objects with { id: <number> } by another list containing the order of those ids
/**
* Helper type for the 'sortByListOfIds' function so we can guarantee the object has an 'id' property.
*/
export type WithId = {
id: number;
};
/**
* Sort an array of objects in place by the 'id' key in the object.
*
* @param list The list of objects to sort in place.
* @param order A list with ids defining the order of the objects.
*/
export function sortByListOfIds<T extends WithId>(list: T[], order: number[]) {
list.sort((a, b) => order.indexOf(a.id) - order.indexOf(b.id));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment