Categories
JavaScript Answers

How to Sort a JavaScript Map Object?

Spread the love

We can sort a JavaScript map object by spreading the entries returned by the entries method into an array.

Then we call sort on that to sort the entries.

For instance, we can write:

const map = new Map();
map.set('2-1', "foo");
map.set('0-1', "bar");
map.set('3-1', "baz");
const mapAsc = new Map([...map.entries()].sort());
console.log(mapAsc)

to create a map object with several key-value pairs.

Then we call map.entries to return an iterator with arrays of key-value pairs in the map.

Next, we spread that into an array so we can call sort on it to sort it by the keys.

And then we convert it back to a map with the Map constructor.

Therefore, mapAsc is:

{"0-1" => "bar", "2-1" => "foo", "3-1" => "baz"}

Conclusion

We can sort a JavaScript map object by spreading the entries returned by the entries method into an array.

Then we call sort on that to sort the entries.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *