I have some code that has populated a typescript dictionary.
var dictionaryOfScores: {[id: string]: number } = {};
Now that I have it I would like to sort it by the value (the number).
This dictionary could be quite large so I am hoping there is a solution to handle it in-place.
I've seen that there is a typescript-collections package that could fit my needs but I'm hoping there is a simple solution that doesn't require me to include another library.
Sort JavaScript object by key describes a plain javascript method that could be used to sort this TypeScript object, but it makes a copy, and it doesn't specifically address the TypeScript dictionary.
So the way I did this was:
var dictionaryOfScores: {[id: string]: number } = {
  Fred: 11,
  George: 22,
  Toby: 18,
  Shannon: 15,
}
var sortableArray = Object.entries(dictionaryOfScores);
var sortedArray = sortableArray.sort(([, a], [, b]) => a - b);
var sortedObject = Object.fromEntries(sortedArray);
console.log(sortedObject)
Which should output
{
  Fred:11,
  Shannon:15,
  Toby:18,
  George:22
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With