Home  >  Q&A  >  body text

Sort JavaScript map by decimal key

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.

P粉755863750P粉755863750396 days ago599

reply all(1)I'll reply

  • P粉501683874

    P粉5016838742023-09-20 12:24:53

    Although any type can be used in the key of a Map() object, they are coerced when using the default sort() 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.

    const map = new Map();
    map.set(3, "foo");
    map.set(1, "foo");
    map.set(8, "foo");
    map.set(10, "foo");
    map.set(5, "foo");
    map.set(2, "foo");
    map.set(4, "foo");
    map.set(7, "foo");
    map.set(6, "foo");
    map.set(9, "foo");
    
    // does not work:
    const mapFailedSort =  new Map([...map.entries()].sort());
    console.log(mapFailedSort);
    
    // works:
    const mapAsc = new Map([...map.entries()].sort((a, b) => +a[0] > +b[0] ? 1 : -1));
    console.log(mapAsc)

    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.

    reply
    0
  • Cancelreply