Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

295
Visualizações
Finding the longest word in a string, after converting it to an array

I'm a newbie to javascript development and am currently working my way through free code camp and it's challenges / projects.

I have been asked to write a function to find the longest word out of a string: "The quick brown fox jumped over the lazy dog". This is my code to do this:

function findLongestWordLength(str) {

  let result = 0;                // define result value of 0
  str.split(" ");                // split string into array, separated by spaces
  for(let i = 0; i < str.length; i++) {     // for loop to iterate through each index of array
  let counter = 0;                          // counter equals 0
  counter += str[i].length;     // counter equals to itself + length of the ith index in array
  if(counter > result) {        // if counter is greater than result then result = counter
    result = counter;
  }   
 } 
return result;
}

I'm sure there are many better ways to do this than the one I am doing, and I could simply search for a different/better way to do it and to get around the problem. But, rather than just ignore the mistake and move to a different method, I want to learn from it first, and then maybe after I will tackle the problem a different way. I would really love if someone could point it out to me so I could learn from the mistake wherever I am going wrong.

If anyone also wants to suggest other, probably more efficient methods of doing this please let me know, I'm eager to learn more methods of how to solve these problems :)

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You're making it too complicated. There's nothing you need to count, just compare the length of the strings and keep track of the longest one.

var x = "The big brown fox jumped over a bee.";
var arr = x.split(" ");
var biggest = arr[0];

for (i = 1; i < arr.length; i++) {
  if (arr[i].length > biggest.length)
    biggest = arr[i];
}

console.log(biggest);

about 4 years ago · Juan Pablo Isaza Relatório

0

In your code, you only run str.split(" "); but you are not storing the results back into str

In the comparison, you have to check if the current length in the loop is greater than the one you have already stored in result.

If it is greater, then set it to the new largest value.

You could update the code to

function findLongestWordLength(str) {
    let result = 0;                          // init current result to 0
    const arr = str.split(" ");              // store the splitted string in arr as array (naming it str is not clear anymore in the code)
    
    for (let i = 0; i < arr.length; i++) {   // loop the arr array
        const len = arr[i].length            // for every item in the array, get the string length
        if (len > result) {                  // if the string length here is greater than the one in result 
            result = len;                    // set result to the new maximum length
        }
    }
    return result;                           // at the end of the loop, return the maximum
}

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

about 4 years ago · Juan Pablo Isaza Relatório

0

I'd do it this way, in one line :

const input = "The quick brown fox jumped over the lazy dog";

const longestWord = sentence => sentence.split(" ").map(word => word.length).sort().pop();

console.log(longestWord(input))

Explanation :

sentence
     .split(" ") // [ "The", "quick", "brown" ...... ]
     .map(word => word.length) // [ 3, 5, 5, 3, 6, 4, 3, 4, 3]
     .sort() // [3, 3, 3, 3, 4, 5, 5, 6]
     .pop(); // 6
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda