skip to Main Content

Hello I tryed converting a string to array and then finding the biggest word, output should be length of the word in numbers. Im not sure what im doing wrong and why this code is not working if someone could point it out for me I would be very grateful.

function findLongestWordLength(str) {
  let words=str.split(" ");
  let bigword=0;
  
  for(let i=0; i<=words.length; i++) {
      if(words[i].length>bigword) {
          bigword=words[i].length;
      }
  }
  return bigword; 
}

5

Answers


  1. In your for loop, you are iterating a bit far away.
    You can replace i<= words.length by i< words.length

    Login or Signup to reply.
  2. It’s because your loop runs longer than there is elements in array.

    Change i<=words.length to i<words.length

    function findLongestWordLength(str) {
      let words = str.split(" ");
      let bigword = 0;
    
    
      for (let i = 0; i < words.length; i++) {
    
        if (words[i].length > bigword) {
          bigword = words[i].length;
        }
    
      }
      
      return bigword;
    }
    
    console.log(findLongestWordLength('a aaa bb c'));
    Login or Signup to reply.
  3. You can also use Math.max with passed mapped array of words lengths:

    const findLongest = (str) => {
      const words = str.split(' ');
      const longest = Math.max(...words.map(({ length }) => length));
      return longest;
    };
    
    const str = 'This is the test string';
    const longestLength = findLongest(str);
    console.log(longestLength); 
    Login or Signup to reply.
  4. function findLongestWordLength(str) {
        let words = str.split(" ");
        let biglength = Math.max(...words.map(({ length }) => length));
        let word = [];
        for (let i = 0; i < words.length; i++) {
            if (words[i].length == biglength) {
                word.push(words[i]);
            }
        }
        return word;
    }
    console.log(findLongestWordLength('a bb ccc ddd ee f'));
    
    Login or Signup to reply.
  5. function findBigestWordLength(wordsParams) {
      const words = wordsParams.split(' ');
    
      console.log(Math.max(...words.map((word) => word.length)));
    }
    
    findBigestWordLength('a bb ccc dddd eeeee');
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search