Longest word in a sentence
Medium
16
76.1% Acceptance
In this coding challenge, you will be implementing a function findLongestWord(sentence)
that takes a string sentence
as its argument and returns the longest word in it. If there are two or more words of the same length, then the function should return the word whose’ first occurrence has a smaller index.
Instructions
- If no such word is found then return
null
. - You can assume that the sentence is always a valid and properly formatted human sentence where words are separated by just one whitespace.
- The function should be exported properly using ESM Syntax.
Example test cases
const sentence = 'Welcome to reacterry'; findLongestWord(sentence); // Output: 'reacterry'
const sentence = ''; findLongestWord(sentence); // Output: null
Hints
- You should start by converting the string
sentence
into an array of words, this way the problem will be much easier to reason about. - You should iterate over each element in the array and keep track of the current longest word and its index.