Reduce Finding the Longest Word in a String

Tell us what’s happening:
Hi to all,
I have solved problem with simple array, but i’m curious to see other solutions in hint and i have seen the reduce version of it, but i cant’ understand it.

Can someone explain what is going on in this function after the split ?

What is the role of x and y ?
x is the accumulator ?
y seems to be the lenght of the current string compared with the index x ?
What the 0 stands for ?

Thanks

Your code so far


function findLongestWordLengthReduce(s) {
    return s.split(' ')
        .reduce(function (x, y) {
            return Math.max(x, y.length)
        }, 0);
}

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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.3; Win64; x64; rv:64.0) Gecko/20100101 Firefox/64.0.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/find-the-longest-word-in-a-string

Reduce takes two arguments: the first is the callback (where here x is the accumulator, but y is just the current item in the array, which is why it uses y.length), the second is the value the accumulator starts at.

If you leave off that second argument, then reduce will take the first value in the array as the value the accumulator starts at (which in this case would cause the solution to break, as the first value is a string, but the accumulator has to be a number)

2 Likes