如何找到字符串中最长的单词并返回那些(不包括重复项)以及最大长度?

Tra*_*e12 8 javascript arrays string

我知道如何找到字符串中最长的单词。例如这里的代码。但这里的问题是找到了“bbbbbb”这个词,因为他是字符串中第一个最长的词,在 6 个字符之后,我们还有“跳跃”这个词。我的问题是在这种情况下我怎么能找到“跳跃”这个词,所以他们不仅仅是第一个。

更新:我想要唯一的列表,所以每个单词只有一个

function longestWord(sentence) {
  sentence = sentence.split(' ');

  let theWord = sentence[0];
  var longest = 0;
  for (let i = 0; i < sentence.length; i++) {
    if (sentence[i] != "") {
      if (sentence[i].length > theWord.length) {
        longest = sentence[i].length;
        theWord = sentence[i];
      }
    }
  }
  return {
    length: longest,
    actuallWord: theWord
  }
}
console.log(longestWord("The quick brown as bbbbbb fox jumped over the bbbbbb lazy dog"));
Run Code Online (Sandbox Code Playgroud)

Lui*_*noz 9

function longestWord(sentence) {
  // First we divide the sentence into words
  var words = sentence.split(' ');
  
  // We then get the length by getting the maximun value of the length of each word
  var length = Math.max(...words.map(a=>a.length));
  return {
    length: length,
    // Finally we filter our words array returning only those of with the same length we previously calculated
    words: words.filter(i => i.length == length)
  }
}
console.log(longestWord("The quick brown as bbbbbb fox jumped over the lazy dog"));
Run Code Online (Sandbox Code Playgroud)

  • @LuisfelipeDejesusMunoz 为什么不添加解释呢?这对于找到这个答案的其他读者来说是有好处的。除了OP。 (3认同)