How to use IF statement inside .reduce Method

Tell us what’s happening:
I am trying to use IF Statement conditions inside .reduce Method of what seems to work when using Ternary operator, but I’m not sure if this is even possible or am I missing something?

  **Your code so far**

function findLongestWordLength(str) {
// return str.length;

// Doesn't work:
return str.split(' ').reduce((longest, current) =>{
if ( current.length > longest)
      longest = current.length; // I tried `current.length = longest;`, but of course that is impossible
// return current.length;
// // But this WORKS:
// const strIntoArray = str.split(' ');
// return strIntoArray.reduce((longest, current) => current.length > longest ? current.length: longest, 0)


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/100.0.4896.127 Safari/537.36

Challenge: Find the Longest Word in a String

Link to the challenge:

I don’t think you’re supposed to assign something on longest here.

How do you read the ternary operator version?

1 Like

I’m not sure if I understood correctly, you asked me how I came up with the idea of my ternary operator solution?

I was trying to make it work with the IF statement, googled stuff and found on stackoverflow a ternary operator solution closest to my logic, modified it a little and to my surprise it worked.

If you meant what was my logic behind it?
I split the string into array of words using split() method, then I wanted to compare each of those element’s length and let the longest persevere and return its value using .reduce() method.
->on comparison between the currentValue > accumulativeValue Condition is checked:
If the currentValue is bigger, then the accumulativeValue (longest) will get its length (count) and be compared against the next currentValue.length.

Here’s how I read your ternary operator:
If current.length is greater than longest, we return the current.length, otherwise, we return longest.

Having the same logic with the if statement and it should work.

Inside your if you aren’t returning anything. The point isn’t to change longest but to return the value that will become the new longest.

1 Like

Hey yes I noticed that I have commented it out in my “to be asked on forum” code, prior to that i had tested 8 different ways with return statement included and they all failed, i gave up and saw the solutions, passed it, then asked mysef “so i guess i still dont know the limits of reduce()?”, then went back to that challenge and wrote the code i could recall while half-awake.

So here my point is you can use the commented return statement (as it was indeed included in my tests) but I will also try to edit my code as it is my first time asking coding question on this forum :ok_hand:

I will try to come back with a reply if I managed to make it work or have a further question.
To be honest I’m still trying to understand .reduce() as it is still my weakness, its why the code looks messy as my understanding in my head is still messy.

Ok so my human logic is impossible to be translated into .split(' ').reduce() method.
It is possible only by using the Math.max() function like:

return Math.max(longest, current.length)


.reduce((longest, current) => //here )

Which is a solution 99% close to my logic, but the weird part is: I decided to console.log() everything and console.log(longest.length) is returning undefined everytime, but the MAGIC is console.log(longest) is returning a correct .length (instead of a word).

While my original code works ONLY for array elements that are only numbers, but not words(strings) because I can’t set .length property to be another’s element .length.

The magical code that works for strings in array:

function findLongestWordLength(str) {
    return str.split(' ').reduce(function(longest, current) {
      console.log('longest.length:', longest.length) //returns 'UNDEFINED'
      console.log('current.length:', current.length)
      console.log('longest word:', longest) //returns .LENGTH of the 'undefined' strings
      console.log('current word:', current)
      console.log('Math.max(longest, current.length):', Math.max(longest, current.length))
      return Math.max(longest, current.length)
    }, 0);

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

First, I like that you’re utilizing the use of debugging in JavaScript, keep that up.

I would log what longest and current parameters return:

console.log(`longest is 
${longest}`, `current
 is ${current}`)

I got the idea of using template literals from Kevin. Feels like the code is talking to me. (thanks! :smiley:)

Now, regarding this:

You’re logging the length of longest (which is 0), thus, it’s returning undefined.

That’s because you’re comparing the numbers 0 and current.length (in which turns to 6 because of the Math.max function) and so that would be comparing 0 and 6.

I don’t think there’s a reason it would return a string?

1 Like

Thanks, that clarifies my confusion.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.