DEV Community

Discussion on: Find longest word in a given string

Collapse
 
dionakra profile image
David de los Santos Boix • Edited

Same thing, but using a reducer instead of sorting.

const getLongestWordOf = (sentence = '') => {
  return sentence
    .split(' ')
    .reduce((longest, current) => {
      return current.length > longest.length ? current : longest;
    })

}

getLongestWordOf('I am just another solution to the same problem');

EDIT: This approach seems to be faster than the sorting one! jsperf.com/longestwordjs/1

Collapse
 
nektro profile image
Meghan (she/her)

This is what I thought to do as well 😄

Collapse
 
abhidon profile image
Abhinay Donadula

Good one, didn't think of reduce 👏