Basic Algorithm Scripting: Find the Longest Word in a String (return question)

So I know that in this code it is returning something. But it’s not returning the right thing.

Is my variable theLongest only returning the first longest string it finds and not comparing it to others?

And are arr[i] and arr[j] just comparing the same words? Meaning that comparing them would be meaningless?

Your code so far

function findLongestWordLength(str) {
var arr = str.split(" ");
var arr2 = [...arr];
var theLongest;

for (let i=0; i < arr.length; i++){
  for (let j=0; j < arr2.length;j++){
    if (arr[i].length > arr[j].length){  
      theLongest = arr[i].length;
      return theLongest;

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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36.

Challenge: Find the Longest Word in a String

Link to the challenge:

same words various time over. You really need one single loop.

yep. Once a return statement is met, the function returns a value and stop there.

1 Like

I see! Thank you! :slight_smile: