Find the Longest Word in a String using Reduce

Find the Longest Word in a String using Reduce
0

#1

Can anyone explain why does my code not work? I can get it to log "jumped’ if I type “return prev” instead of “return prev.length” but I can’t get it to log 6.

function findLongestWord(str) {
return str.split(’ ').reduce(function (prev, curr) {
if (prev.length > curr.length) {
return prev.length;
} else {
return curr.length;
}
});
}

findLongestWord(“The quick brown fox jumped over the lazy dog”);


#2

The first time the reduce function runs, prev is a string and has a .length property. But you return a number and prev becomes that number.

The next iteration of reduce is run and you try to get the value of prev.length - that’s a string property, not a number property.

If you stick to returning strings and then, when reduce is done, return the length of the reduce result, it should work fine.

~Micheal


#3

The issue is that when you return prev.length you are returning a number. Javascript evaluates the number then as a string, with a length of one.

EDIT: Ah, beaten to the punch!


#4

okay, gotcha. That makes sense.

Thanks!