admin管理员组

文章数量:1288048

I know how I can find the longest word in a string. For example this code here. But here the problem is that the word "bbbbbb" is found because he is the FIRST LONGEST WORD IN THE string,after that with 6 chars we have also the word "jumped". My question is how can I find in this case and the word "jumped",so all of them not only the first one.

UPDATE: I want unique list, so only one of each words

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"));

I know how I can find the longest word in a string. For example this code here. But here the problem is that the word "bbbbbb" is found because he is the FIRST LONGEST WORD IN THE string,after that with 6 chars we have also the word "jumped". My question is how can I find in this case and the word "jumped",so all of them not only the first one.

UPDATE: I want unique list, so only one of each words

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"));

Share Improve this question edited Feb 10, 2020 at 16:19 mplungjan 178k28 gold badges181 silver badges240 bronze badges asked Feb 10, 2020 at 14:50 Trajce12Trajce12 3615 silver badges17 bronze badges 3
  • Try sentence.filter(w => w.length === longest) to get an array of words with that length. – Rafi Commented Feb 10, 2020 at 14:58
  • You can try creating an array to hold the longest words that you add to. Then you can use filter() or map() to evaluate length and add to the array. – CoderLee Commented Feb 10, 2020 at 15:01
  • You have two answers with unique words now: Yevhen's and FZs – mplungjan Commented Feb 10, 2020 at 15:36
Add a ment  | 

7 Answers 7

Reset to default 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"));

You could take a single loop approach and check the legth fot each word with the accumulators length of the first item.

function longestWords(words) {
    return words
        .split(/\s+/)
        .reduce((accu, word) => {
            if (!accu[0] || accu[0].length < word.length) return [word];
            if (accu[0].length === word.length) accu.push(word);
            return accu;
        }, []);
}

console.log(longestWords("The quick brown as bbbbbb fox jumped over the lazy dog"));

You may do that with Array.prototype.reduce() by a single pass through the array (without extra looping for calculating maximum length).

The idea is to reset resulting array with a single word, once its length exceeds those that were inserted before or append if current word happens to have same length, or simply pass by otherwise:

const src = 'The quick brown as bbbbbb fox jumped over the jumped lazy dog',

      result = src.split(' ')
                  .reduce((res, word, idx) => {
                    if(!idx || word.length > res.length)
                        res = {length: word.length, words:new Set([word])}
                    else if(word.length == res.length)
                        res.words.add(word)
                    return res
                  }, {})

console.log({result: result.length, words: [...result.words]})
.as-console-wrapper {min-height:100%}

You can do it by reducing the sentence array.

The advantage of this approach is that it loops over the array only once:

function longestWords(sentence) {
  return sentence.split(' ').reduce((output, word) => {
    if (word.length > output.length) {
      output.words = [word]
      output.length = word.length
    } else if (word.length === output.length) {
      output.words.push(word)
    }
    return output
  }, { length: 0, words: [] })
}
console.log(longestWords("The quick brown as bbbbbb fox jumped over the lazy dog"));

Or, if you want to filter out duplicate words, you could return a Set instead:

function longestWords(sentence) {
  return sentence.split(' ').reduce((output, word) => {
    if (word.length > output.length) {
      output.words.clear()
      output.length = word.length
    } 
    if (word.length >= output.length) {
      output.words.add(word)
    }
    return output
  }, { length: 0, words: new Set })
}
const words = longestWords("The quick brown as bbbbbb fox jumped over the jumped lazy dog")
console.log(words.length);
console.log(Array.from(words.words)) //Just to make StackSnippets console show the Set's entries

What you can do is check if the word's length is greater or equal to the length of the first item of the array (All the items in the array should have the same length).

If so, then check if it is greater. If that is true, then set the array to that word, because you found a word that was bigger than the words in the array. Otherwise, add it to the array of the words that have the greatest length.

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[0].length) {
        if (sentence[i].length > theWord[0].length) {
          longest = sentence[i].length;
          theWord = [sentence[i]];
        } else {
          theWord.push(sentence[i])
        }
      }
    }
  }
  return {
    length: longest,
    actuallWord: theWord
  }
}
console.log(longestWord("The quick brown as bbbbbb fox jumped over the lazy dog"));

It can also be done in single reduce.
Initiated with the object.

function longestWord(words) {
  return words
    .split(/\s+/)
    .reduce((acc, word) => {
  	if(word.length > acc.length) {
  		acc.length = word.length;
  		acc.words = [word];
  	}
  	else if (word.length === acc.length) {
  		acc.words.push(word);
  	}
  	return acc;
  }, {length:0, words:[]});
}

console.log(longestWord("The quick brown as bbbbbb fox jumped over the lazy dog"));

This approach doesn't have a better time plexity than the best answers here, but it does have better coefficients. (It only loops over the array of words once, no function calls except for Array.prototype.push).

let allLongestItems = items => {
  let longest = [];
  let length = 0;
  for (let item of items) {
    let len = item.length;
    if (len === length) longest.push(item)
    else if (len > length) { longest = [ item ]; length = len; }
  }
  return { items: longest, length };
};

let str = 'The quick brown as bbbbbb fox jumped over the lazy dog';
console.log(allLongestItems(str.split(' ')));

本文标签: