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)