find the kth most common element in an array in typescript

Here's an example implementation that finds the kth most common element in an array using TypeScript:

index.ts
function findKthMostCommon(arr: number[], k: number): number | undefined {
  // Create a dictionary to count the occurrences of each element in the array
  const dict: Record<number, number> = {};
  arr.forEach(num => {
    dict[num] = dict[num] ? dict[num] + 1 : 1;
  });

  // Convert the dictionary into an array of [key, value] pairs
  const pairs = Object.entries(dict);

  // Sort the pairs array by descending order of values (occurrence counts)
  pairs.sort((pairA, pairB) => {
    return pairB[1] - pairA[1];
  });

  // Return the value of the kth most common element
  if (pairs[k - 1]) {
    return parseInt(pairs[k - 1][0]);
  } else {
    return undefined;
  }
}
677 chars
23 lines

This implementation first creates a dictionary to count the occurrences of each element in the array. It then converts the dictionary into an array of [key, value] pairs and sorts the array by descending order of values (occurrence counts). Finally, it returns the value of the kth most common element in the array.

Note that this implementation assumes that the input array contains only numbers. If the input array can contain non-numeric values, you may need to modify the implementation accordingly.

gistlibby LogSnag