find the kth largest number in a list in typescript

To find the kth largest number in a list using typescript, we first sort the list in descending order using the built-in sort function. Then, we can simply return the element at the kth index.

Here's the code:

index.ts
function findKthLargestNumber(list: number[], k: number): number {
  list.sort((a, b) => b - a); // Sort in descending order
  return list[k - 1]; // Return the kth largest number
}
182 chars
5 lines

This function takes in a list of numbers and the value of k, and returns the kth largest number in the list. Note that we subtract 1 from k when returning the element since array indexing starts from 0.

Example usage:

index.ts
const list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];
const k = 3;

const result = findKthLargestNumber(list, k);
console.log(result); // Output: 5
142 chars
6 lines

In this example, the 3rd largest number in the list is 5, so the output of the function is 5.

gistlibby LogSnag