I have a map with a key of month and a key value of 1
... 31
. If I understand correctly, JavaScript converts the map's keys to strings.
Use the standard new Map([...myMap.entries()].sort())
After sorting, the map is sorted by key as follows:
1, 11, 12, 13, ..., 19, 2, 20, 21, 22, 23, ... 29, 3, 30, 31.
I found a way to convert the decimal key to a string and fill the single numbers with 0
to achieve 1,2,3,4,5, ...
Sort by:
mykey.toString().padStart(2, "0");
I suspect this approach is too contrived and there should be some pre-built JavaScript method to achieve normal map sorting by the decimal value of the key.
Any suggestions on how to sort JavaScript maps by decimal key in a better way?
Triednew Map([...myMap.entries()].sort())
- The map was sorted as: 1, 11, 12, ..., 19, 2, 20 , 21, 22, ... 29, 3, 30, 31.
Although any type can be used in the
key
of aMap()
object, they are coerced when using the defaultsort()
implementation Convert to string.To solve this problem, you need to implement your own sorting logic to explicitly compare them as numerical values. In the example below it uses integers, but this can be easily updated to use
parseFloat()
if decimal comparisons are required.Note: The code snippet console appears to be incompatible with
Map()
objects - please check the output in the dev tools console to see if the ordering is correct.