Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

294
Views
Encontrar la palabra más larga en una cadena, después de convertirla en una matriz

Soy un novato en el desarrollo de JavaScript y actualmente estoy trabajando en el campamento de código libre y sus desafíos/proyectos.

Me han pedido que escriba una función para encontrar la palabra más larga de una cadena: "El veloz zorro marrón saltó sobre el perro perezoso". Este es mi código para hacer esto:

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

Estoy seguro de que hay muchas maneras mejores de hacer esto que la que estoy haciendo, y simplemente podría buscar una manera diferente/mejor de hacerlo y solucionar el problema. Pero, en lugar de simplemente ignorar el error y pasar a un método diferente, primero quiero aprender de él, y luego quizás abordar el problema de una manera diferente. Realmente me encantaría que alguien pudiera señalarme para poder aprender del error donde sea que me esté equivocando.

Si alguien también quiere sugerir otros métodos, probablemente más eficientes, para hacer esto, hágamelo saber, estoy ansioso por aprender más métodos sobre cómo resolver estos problemas :)

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Lo estás complicando demasiado. No hay nada que necesites contar, solo compara la longitud de las cuerdas y realiza un seguimiento de la más larga.

 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 Report

0

En su código, solo ejecuta str.split(" "); pero no está almacenando los resultados nuevamente en str

En la comparación, debe verificar si la longitud actual en el ciclo es mayor que la que ya ha almacenado en el resultado.

Si es mayor, configúrelo en el nuevo valor más grande.

Podrías actualizar el código a

 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 Report

0

Lo haría de esta manera, en una línea:

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

Explicación :

 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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!