Sometimes, we want to sort a ES6 map object with JavaScript.
In this article, we’ll look at how to sort a ES6 map object with JavaScript.
How to sort a ES6 map object with JavaScript?
To sort a ES6 map object with JavaScript, we convert the map to an array, sort that, and then convert the sorted array back into a map.
For instance, we write
const sortedMap = new Map(
[...map].sort((a, b) => {
// ...
})
);
to convert the map
to an array with [...map]
.
Then we call sort
with a callback to sort the array.
And then we convert the sorted array back to a map using the Map
constructor.
Conclusion
To sort a ES6 map object with JavaScript, we convert the map to an array, sort that, and then convert the sorted array back into a map.