Cybernetic
Cybernetic

Reputation: 13334

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?

Upvotes: 1

Views: 99

Answers (4)

0stone0
0stone0

Reputation: 43983

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]);
}

Upvotes: 0

Nick
Nick

Reputation: 6362

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)

Upvotes: 0

Unmitigated
Unmitigated

Reputation: 89284

You can use Array#slice.

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

Upvotes: 2

Anonymous
Anonymous

Reputation: 754

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.

Upvotes: 0

Related Questions