Sorting maps
Just like lists, maps can be sorted too. To preserve the new order of the map once it's sorted, you have to convert it to an ordered map. You can also sort maps by their keys.
Creating ordered maps
Maps have a sort()
method, just like lists. They even use the same default comparator function. To preserve the order of the map after sort()
has been called, you can use toOrderedMap()
to convert it, as follows:
const myMap = Map.of( 'three', 3, 'one', 1, 'four', 4, 'two', 2 ); const mySortedMap = myMap .toOrderedMap() .sort(); myMap.forEach( (v, k) => console.log('myMap', `${k} => ${v}`) ); // -> myMap three => 3 // -> myMap one => 1 // -> myMap four => 4 // -> myMap two => 2 mySortedMap.forEach( (v, k) => console.log('mySortedMap', `${k} => ${v}`) ); // -> mySortedMap one => 1 // -> mySortedMap two => 2 // -> mySortedMap three => 3 // -> mySortedMap four => 4
The semantics of sort()
are the same for lists...