I have a map with keys = day of the month, 1
… 31
. If I understand correctly, Javascript converts the map keys into strings anyways.
After sorting using the standard new Map([...myMap.entries()].sort())
the map becomes sorted by the keys as:
1, 11, 12, 13, ..., 19, 2, 20, 21, 22, 23, ... 29, 3, 30, 31.
I found a way to sort as 1,2,3,4,5, ...
by converting the decimal keys to strings and pad single numbers with 0
:
mykey.toString().padStart(2, "0");
I suspect this is too artificial and there should be some pre-built in Javascript method to achieve the normal sort of a map by a decimal values of the keys.
Any suggestions how to sort Javascript map by decimal keys in a nicer way?
Tried new Map([…myMap.entries()].sort()) – the map got sorted as : 1, 11, 12, …, 19, 2, 20, 21, 22, … 29, 3, 30, 31.
2
Answers
While any type can be used in the
key
of aMap()
object, when using the defaultsort()
implementation they are coerced to strings.To fix this you need to implement your own sorting logic which explicitly compares them as numeric values. In the example below it uses integers, but this can easily be updated to use
parseFloat()
if decimal comparison is required.Note: The snippet console doesn’t appear to play very nicely with
Map()
objects – check the output in the devtools console to see the sorting has worked correctly.You can sort keys instead of entries, this will give you better performance since you don’t create and copy array data for values. To sort the keys as numbers you should provide a custom comparator function otherwise the keys will be sorted as strings:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
And the benchmark with a big map (a small map looks the same):