1

我们可以在这样的字符串中找到最长的单词:

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

如何有效地找到前 n 个最长的单词?例如,如何提取前 3 个最长的单词,而不仅仅是最长

4

4 回答 4

2

您可以使用Array#slice.

str.split(" ").sort(function(a, b) {return b.length - a.length}).slice(0,3)
于 2021-02-20T22:33:40.900 回答
0

由于.sort返回按您的顺序排序的所有元素,因此您可以循环结果。

删除[0]部分代码以保留所有元素。

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

于 2021-02-20T22:38:41.993 回答
0

你想要一个从上到下排列的列表吗?这就是排序的目的。您已经有了列表,只需[0]从行尾删除 ,因为这意味着“访问列表的第一项”,并将其替换为,例如,slice(0, 3)获取最后 3 项。

于 2021-02-20T22:33:34.350 回答
0

如果您不关心获得唯一的单词,则可以使用该slice方法。

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

但是如果同一个词出现多次,你可能会在输出中多次出现。例如,“foo bar fooy fooy”会导致['fooy', 'fooy', 'bar'].

要消除此问题,请先将初始数组转换为集合。

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)

于 2021-02-20T22:37:20.267 回答