1

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?

Unmitigated
  • 76,500
  • 11
  • 62
  • 80
Cybernetic
  • 12,628
  • 16
  • 93
  • 132
  • 2
    Why wouldn't you just replace the `[0]` with, say some notation to slice out the first 3 items in the sorted array? I'm rusty with JS, but in Python it would be `[:3]`. I think it's `.slice(0, 3)`? – Arya McCarthy Feb 20 '21 at 22:32
  • As Arya said, you can slice and get 'n' words: Example: str.split(" ").sort(function(a, b) {return b.length - a.length}).slice(0,3) – Peres Feb 20 '21 at 22:35
  • With a top n heap sort. – Jonas Wilms Feb 20 '21 at 22:49

4 Answers4

2

You can use Array#slice.

str.split(" ").sort(function(a, b) {return b.length - a.length}).slice(0,3)
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
0

Do you want a list, ranked from top to bottom? That's what sorting is for. You already have the list, just remove the [0] from the end of the line because that means "access the first item of the list", and replace it with, say, slice(0, 3) to get the last 3 items.

Anonymous
  • 738
  • 4
  • 14
  • 36
0

If you don't care about getting unique words, you can use the slice method.

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

But if the same word appeared multiple times, you might get it multiple times in the output. For instance, "foo bar fooy fooy" would result in ['fooy', 'fooy', 'bar'].

To eliminate this issue, convert the initial array into a set first.

const str = 'foo bar fooy fooy'
const n = 2
const words = str.split(" ")
const uniqueWords = [...new Set(words)]
const longestWords = uniqueWords.sort((a, b) => b.length - a.length).slice(0, n)
console.log(longestWords)
Nick
  • 5,108
  • 2
  • 25
  • 58
0

Since .sort returns all the elements, sorted in your order, you can just loop of the result.

Remove the [0] part of your code to keep all elements.

const string = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.';
const counted = string.split(' ').sort(function(a, b) {return b.length - a.length});

for (let i = 0; i < 3; i++) {
   console.log(i, counted[i]);
}
0stone0
  • 34,288
  • 4
  • 39
  • 64