DEV Community

Discussion on: 5 useful javascript tricks for begginers.

Collapse
 
danim47c profile image
Daniel Mateos

I think the best way you can obtain the most lengthy string in an array is this:

const mostLengthy = someArray
    .reduce((acc, i) =>
        i.length > acc.length
             ? i
             : acc
)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
developeratul profile image
Info Comment hidden by post author - thread only visible in this permalink
Minhazur Rahman Ratul

useful :)

Collapse
 
coderslang profile image
Coderslang: Become a Software Engineer

That's a good one, although it might be useful to first filter out nulls and undefineds from the array:

const mostLengthy = someArray
    .filter(item => item)
    .reduce((acc, i) => i.length > acc.length ? i : acc);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
mdegoys profile image
Matthieu • Edited

You can also do this way I believe (sort by the length of the words in descending order, then pick the first one).

const mostLengthy = someArray.sort((x, y) => y.length - x.length)[0] 
Enter fullscreen mode Exit fullscreen mode

Maybe it's more understandable ? But I agree reduce is great :).

Some comments have been hidden by the post's author - find out more