-3

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.

SRobertJames
  • 8,210
  • 14
  • 60
  • 107
  • 1
    This is not distinct from the question you linked. Your sorting will depend on what you pass to `.sort`. – Zac Anger Apr 25 '23 at 00:55
  • and [How to sort an array of integers correctly](https://stackoverflow.com/questions/1063007/how-to-sort-an-array-of-integers-correctly) – pilchard Apr 25 '23 at 01:09

1 Answers1

1

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
AngYC
  • 3,051
  • 6
  • 20