Search code examples
javascriptnode.jssortingcollectionskey-value

Sort a Javascript Map by value numerically


If kv is a Javascript Map object, how can I sort it by its value numerically?

This is, for example, a common pattern when kv is a counter, and we need to see the top-n items with the highest count.

This is distinct from Is it possible to sort a ES6 map object? , which is lexical sort.


Solution

  • You can pass in the first argument in the Array.prototype.sort() function

    An example for your case would be:

    [...kv.values()].sort((a, b) => a - b);

    Explanation:

    1. You obtain the the Value Iterator for your Map object using Map.prototype.values() function
    2. Then you spread it using [...iterator] pattern to convert it into an array
    3. Last you use the sort function with Array.prototype.sort(). The first parameter allow you to pass in a comparator function, where:
    compareFn(a, b) return value sort order
    > 0 sort a after b, e.g. [b, a]
    < 0 sort a before b, e.g. [a, b]
    === 0 keep original order of a and b