Created
May 19, 2022 11:23
-
-
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
This file contains hidden or 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
/** | |
* 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