Get the longest word from sentence algorithm problem with javascript

Viewed 50

I am building an algorithm of my own that is supposed to return the longest word from a sentence with javascript. The custom algorithm is compiling but returning an incorrect string. Am trying to solve programming problems without plagiarising so please help....

logic

a) Form an array out of the sentence using .split(" ") function.

b) Define a variable index that will be used to store the index of the element with the largest length

c) Define a default string mystring that we will use for comparisons in the loop

d) Iterate through the array we formed in step while comparing each string at each index with our variable mystring, if the string at the specified position is larger than our mystring,we get the index of that string and store it in the index variable..

e) We return the string at the index of the array that we got from the loop

Expectations

For a sample sentence like I love the United States of America,the algorithm should return America as the longest string. Instead its returning United which is false. The rest of the problem is commented in my code below

Code

function longestWord(sentence) {
  //we use this index to store the index of the 
  //longest word in the array
  let index = 0;
  //define an empty string for comparison
  let mystring = "";
  //define a new array
  let arr = sentence.split(" ");
  //iterate through the array
  for (let p = 0; p < arr.length; p++) {
    if (arr[p].length > mystring.length) {
      //get the index and store in the variable
      index = p;

    }
  }
  //return the element at the index we got
  return arr[index];
}
console.log(longestWord("I love the United States of America"));
//function returns United, please help

1 Answers

you forgot to change the mystring variable valut to the new string value.

try this :

      function longestWord(sentence) {
       //we use this index to store the index of the 
       //longest word in the array
       let index = 0;
       //define an empty string for comparison
       let mystring = "";
       //define a new array
      let arr = sentence.split(" ");
      //iterate through the array
      for (let p = 0; p < arr.length; p++) {
      if (arr[p].length > mystring.length) {
        //get the index and store in the variable
        index = p;
        mystring=arr[index];

      }
   }
     //return the element at the index we got
     return arr[index];
  }
  console.log(longestWord("I love the United States of America"));
Related