find the kth largest number in a list in javascript

One approach to find the kth largest number in a list is to sort the array in descending order and then return the element at the k-1 index. Here's a code snippet to implement this approach in JavaScript:

index.tsx
function findKthLargest(nums, k) {
  // sort the array in descending order
  nums.sort((a, b) => b - a);
  // return the kth largest element
  return nums[k-1];
}
163 chars
7 lines

You can call this function with an array of numbers and the value of k to get the kth largest number.

index.tsx
const arr = [3, 1, 4, 2, 5];
const k = 3;
console.log(findKthLargest(arr, k)); // output: 3
92 chars
4 lines

Note that this approach has a time complexity of O(n log n) due to the sorting algorithm used. There are other approaches that have better time complexity, such as using a modified binary search algorithm to find the kth largest element in O(n) time.

gistlibby LogSnag