One way to find the kth longest word in a string in JavaScript is by splitting the string into an array of words, sorting the array by decreasing length, and returning the word at index k-1
. Here's an implementation:
263 chars10 lines
In this example, we split the string str
into an array of words using the split()
method with a space delimiter. We then sort the array by the length of each word using the sort()
method with a comparator function that sorts in decreasing order (b.length - a.length
).
Finally, we return the word at index k-1
. Note that we subtract 1 from k
since array indices start from 0 in JavaScript.
For the example input, the kthLongestWord
function returns 'jumps'
, which is the second longest word in the string (k=2
).
gistlibby LogSnag