javascriptstringsortingcharactercount

Find n longest words in string efficiently


We can find the longest word in a string like this:

str.split(" ").sort(function(a, b) {return b.length - a.length})[0];

How can one find the top n longest words efficiently? For example, how can I extract the top 3 longest words, not just the longest?


Solution

  • You can use Array#slice.

    str.split(" ").sort(function(a, b) {return b.length - a.length}).slice(0,3)