find the kth longest word in a string in javascript

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:

function kthLongestWord(str, k) {
  const words = str.split(' ');
  words.sort((a, b) => b.length - a.length);
  return words[k - 1];
}

const str = 'The quick brown fox jumps over the lazy dog';
const k = 2;
const kthLongest = kthLongestWord(str, k); // 'jumps'
263 chars
10 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