How to implement top n problem with JavaScript? For example, most_common () of python

We know that the collections of the python built-in module has a lot of useful operations.
for example:

from collections import Counter
-sharp
-sharp top n
user_counter = Counter("abbafafpskaag")
print(user_counter.most_common(3)) -sharp[("a", 5), ("f", 2), ("b", 2)]
print(user_counter["a"]) -sharp 5

how would you implement it with js? Or is there a built wheel with such an operation in it?

implement most_common: in python

    def most_common(self, n=None):
        """List the n most common elements and their counts from the most
        common to the least.  If n is None, then list all element counts.

        >>> Counter("abcdeabcdabcaba").most_common(3)
        [("a", 5), ("b", 4), ("c", 3)]

        """
        -sharp Emulate Bag.sortedByCount from Smalltalk
        if n is None:
            return sorted(self.items(), key=_itemgetter(1), reverse=True)
        return _heapq.nlargest(n, self.items(), key=_itemgetter(1))

A _ heapq heap data structure is used here, which means that it is a heap to solve the top n problem, not to traverse it. What are the similar wheels for js

"Note:" the traversal method can be implemented by str.split () .

in fact, the essence of this problem is using heap to implement Top K algorithm (JS implementation)


I haven't used it, there should be, after all, there are so many libraries in npm, but I haven't searched them.

I think the biggest problem for JS is that you are not sure whether it is

.
  

there is no priority queue, in the native library of JS. You have to implement this on your own. Talking about looking for library.

Menu