Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a simple way to sort a typescript dictionary?

Tags:

typescript

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.

like image 330
Naylor Avatar asked Oct 28 '25 21:10

Naylor


1 Answers

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
}
like image 133
dannash918 Avatar answered Oct 30 '25 18:10

dannash918



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!