Tres formas de encontrar la palabra más larga de una cadena en JavaScript

Este artículo se basa en la secuencia de comandos del algoritmo básico de Free Code Camp " Encuentra la palabra más larga en una cadena ".

En este algoritmo , queremos mirar cada palabra individual y contar cuántas letras hay en cada una. Luego, compare los conteos para determinar qué palabra tiene más caracteres y devuelva la longitud de la palabra más larga.

En este artículo, voy a explicar tres enfoques. Primero con un bucle FOR, segundo usando el método sort () y tercero usando el método reduce ().

Desafío del algoritmo

Devuelve la longitud de la palabra más larga en la oración proporcionada.

Tu respuesta debe ser un número.

Casos de prueba proporcionados

  • findLongestWord ("El zorro marrón rápido saltó sobre el perro perezoso") debería devolver un número
  • findLongestWord ("El rápido zorro marrón saltó sobre el perro perezoso") debería devolver 6
  • findLongestWord ("Que la fuerza te acompañe") debería devolver 5
  • findLongestWord ("Google do a barrel roll") debería devolver 6
  • findLongestWord ("¿Cuál es la velocidad promedio de una golondrina sin carga") debería devolver 8
  • findLongestWord ("¿Qué pasa si probamos una palabra muy larga como otorrinolaringología")debe devolver 19
function findLongestWord(str) { return str.length; } findLongestWord("The quick brown fox jumped over the lazy dog");

1. Encuentre la palabra más larga con un bucle FOR

Para esta solución, usaremos el método String.prototype.split ()

  • El método split () divide un objeto String en una matriz de cadenas al separar la cadena en subcadenas.

Necesitaremos agregar un espacio vacío entre el paréntesis del método split () ,

var strSplit = “The quick brown fox jumped over the lazy dog”.split(‘ ‘);

que generará una matriz de palabras separadas:

var strSplit = [“The”, “quick”, “brown”, “fox”, “jumped”, “over”, “the”, “lazy”, “dog”];

Si no agrega el espacio entre paréntesis, tendrá este resultado:

var strSplit = [“T”, “h”, “e”, “ “, “q”, “u”, “i”, “c”, “k”, “ “, “b”, “r”, “o”, “w”, “n”, “ “, “f”, “o”, “x”, “ “, “j”, “u”, “m”, “p”, “e”, “d”, “ “, “o”, “v”, “e”, “r”, “ “, “t”, “h”, “e”, “ “, “l”, “a”, “z”, “y”, “ “, “d”, “o”, “g”];
function findLongestWord(str) { // Step 1. Split the string into an array of strings var strSplit = str.split(' '); // var strSplit = "The quick brown fox jumped over the lazy dog".split(' '); // var strSplit = ["The", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog"]; // Step 2. Initiate a variable that will hold the length of the longest word var longestWord = 0; // Step 3. Create the FOR loop for(var i = 0; i  longestWord){ // If strSplit[i].length is greater than the word it is compared with... longestWord = strSplit[i].length; // ...then longestWord takes this new value } } /* Here strSplit.length = 9 For each iteration: i = ? i  longestWord)? longestWord = strSplit[i].length 1st iteration: 0 yes 1 if("The".length > 0)? => if(3 > 0)? longestWord = 3 2nd iteration: 1 yes 2 if("quick".length > 3)? => if(5 > 3)? longestWord = 5 3rd iteration: 2 yes 3 if("brown".length > 5)? => if(5 > 5)? longestWord = 5 4th iteration: 3 yes 4 if("fox".length > 5)? => if(3 > 5)? longestWord = 5 5th iteration: 4 yes 5 if("jumped".length > 5)? => if(6 > 5)? longestWord = 6 6th iteration: 5 yes 6 if("over".length > 6)? => if(4 > 6)? longestWord = 6 7th iteration: 6 yes 7 if("the".length > 6)? => if(3 > 6)? longestWord = 6 8th iteration: 7 yes 8 if("lazy".length > 6)? => if(4 > 6)? longestWord = 6 9th iteration: 8 yes 9 if("dog".length > 6)? => if(3 > 6)? longestWord = 6 10th iteration: 9 no End of the FOR Loop*/ //Step 4. Return the longest word return longestWord; // 6 } findLongestWord("The quick brown fox jumped over the lazy dog");

Sin comentarios:

function findLongestWord(str) { var strSplit = str.split(' '); var longestWord = 0; for(var i = 0; i  longestWord){ longestWord = strSplit[i].length; } } return longestWord; } findLongestWord("The quick brown fox jumped over the lazy dog");

2. Encuentra la palabra más larga con el método sort ()

Para esta solución, usaremos el método Array.prototype.sort () para ordenar la matriz por algún criterio de ordenación y luego devolver la longitud del primer elemento de esta matriz.

  • El método sort () ordena los elementos de una matriz en su lugar y devuelve la matriz.

En nuestro caso, si solo ordenamos la matriz

var sortArray = [“The”, “quick”, “brown”, “fox”, “jumped”, “over”, “the”, “lazy”, “dog”].sort();

tendremos esta salida:

var sortArray = [“The”, “brown”, “dog”, “fox”, “jumped”, “lazy”, “over”, “quick”, “the”];

En Unicode, los números van antes de las letras mayúsculas, que vienen antes de las minúsculas.

Necesitamos ordenar los elementos por algún criterio de ordenación,

[].sort(function(firstElement, secondElement) { return secondElement.length — firstElement.length; })

donde la longitud del segundo elemento se compara con la longitud del primer elemento de la matriz.

function findLongestWord(str) { // Step 1. Split the string into an array of strings var strSplit = str.split(' '); // var strSplit = "The quick brown fox jumped over the lazy dog".split(' '); // var strSplit = ["The", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog"]; // Step 2. Sort the elements in the array var longestWord = strSplit.sort(function(a, b) { return b.length - a.length; }); /* Sorting process a b b.length a.length var longestWord "The" "quick" 5 3 ["quick", "The"] "quick" "brown" 5 5 ["quick", "brown", "The"] "brown" "fox" 3 5 ["quick", "brown", "The", "fox"] "fox" "jumped" 6 3 ["jumped", quick", "brown", "The", "fox"] "jumped" "over" 4 6 ["jumped", quick", "brown", "over", "The", "fox"] "over" "the" 3 4 ["jumped", quick", "brown", "over", "The", "fox", "the"] "the" "lazy" 4 3 ["jumped", quick", "brown", "over", "lazy", "The", "fox", "the"] "lazy" "dog" 3 4 ["jumped", quick", "brown", "over", "lazy", "The", "fox", "the", "dog"] */ // Step 3. Return the length of the first element of the array return longestWord[0].length; // var longestWord = ["jumped", "quick", "brown", "over", "lazy", "The", "fox", "the", "dog"]; // longestWord[0]="jumped" => jumped".length => 6 } findLongestWord("The quick brown fox jumped over the lazy dog");

Sin comentarios:

function findLongestWord(str) { var longestWord = str.split(' ').sort(function(a, b) { return b.length - a.length; }); return longestWord[0].length; } findLongestWord("The quick brown fox jumped over the lazy dog");

3. Encuentre la palabra más larga con el método reduce ()

Para esta solución, usaremos Array.prototype.reduce ().

  • El método reduce () aplica una función contra un acumulador y cada valor de la matriz (de izquierda a derecha) para reducirlo a un solo valor.

reduce () ejecuta una función de devolución de llamada una vez para cada elemento presente en la matriz.

Puede proporcionar un valor inicial como segundo argumento para reducir, aquí agregaremos una cadena vacía “”.

[].reduce(function(previousValue, currentValue) {...}, “”);
function findLongestWord(str) { // Step 1. Split the string into an array of strings var strSplit = str.split(' '); // var strSplit = "The quick brown fox jumped over the lazy dog".split(' '); // var strSplit = ["The", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog"]; // Step 2. Use the reduce method var longestWord = strSplit.reduce(function(longest, currentWord) { if(currentWord.length > longest.length) return currentWord; else return longest; }, ""); /* Reduce process currentWord longest currentWord.length longest.length if(currentWord.length > longest.length)? var longestWord "The" "" 3 0 yes "The" "quick" "The" 5 3 yes "quick" "brown" "quick" 5 5 no "quick" "fox" "quick" 3 5 no "quick" "jumped" "quick" 6 5 yes "jumped" "over" "jumped" 4 6 no "jumped" "the" "jumped" 3 6 no "jumped" "lazy" "jumped" 4 6 no "jumped" "dog" "jumped" 3 6 no "jumped" */ // Step 3. Return the length of the longestWord return longestWord.length; // var longestWord = "jumped" // longestWord.length => "jumped".length => 6 } findLongestWord("The quick brown fox jumped over the lazy dog");

Sin comentarios:

function findLongestWord(str) { var longestWord = str.split(' ').reduce(function(longest, currentWord) { return currentWord.length > longest.length ? currentWord : longest; }, ""); return longestWord.length; } findLongestWord("The quick brown fox jumped over the lazy dog");

Espero que hayas encontrado esto util. Esto es parte de mi serie de artículos “Cómo resolver algoritmos de FCC” sobre los desafíos de algoritmos de Free Code Camp, donde propongo varias soluciones y explico paso a paso lo que sucede bajo el capó.

Tres formas de repetir una cadena en JavaScript

En este artículo, explicaré cómo resolver el desafío "Repetir una cadena, repetir una cadena" de freeCodeCamp. Esto involucra…

Two ways to confirm the ending of a String in JavaScript

In this article, I’ll explain how to solve freeCodeCamp’s “Confirm the Ending” challenge.

Three Ways to Reverse a String in JavaScript

This article is based on Free Code Camp Basic Algorithm Scripting “Reverse a String”

Three Ways to Factorialize a Number in JavaScript

This article is based on Free Code Camp Basic Algorithm Scripting “Factorialize a Number”

Two Ways to Check for Palindromes in JavaScript

This article is based on Free Code Camp Basic Algorithm Scripting “Check for Palindromes”.

Three Ways to Title Case a Sentence in JavaScript

This article is based on Free Code Camp Basic Algorithm Scripting “Title Case a Sentence”.

Three ways you can find the largest number in an array using JavaScript

In this article, I’m going to explain how to solve Free Code Camp’s “Return Largest Numbers in Arrays” challenge. This…

If you have your own solution or any suggestions, share them below in the comments.

Or you can follow me on Medium, Twitter, Github and LinkedIn, right after you click the green heart below ;-)

‪#‎StayCurious‬, ‪#‎KeepOnHacking‬ & ‪#‎MakeItHappen‬!

Resources

  • split() method — MDN
  • sort() method — MDN
  • reduce() — MDN
  • String.length — MDN
  • for — MDN