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.
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:
Map.prototype.values()
function[...iterator]
pattern to convert it into an arrayArray.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 |