find the kth most common element in an array in javascript

To find the kth most common element in an array, we need to first count the frequency of each element in the array. Once we have the frequency of each element, we need to sort the frequencies in descending order and return the kth frequency.

Here's the code that implements this:

index.tsx
function kthMostCommonElement(arr, k) {
  // map to track frequency of each element in arr
  const freqMap = new Map();
  
  // calculate frequency of each element in arr
  for (let i = 0; i < arr.length; i++) {
    const currentValue = arr[i];
    const currentFreq = freqMap.get(currentValue) || 0;
    freqMap.set(currentValue, currentFreq + 1);
  }
  
  // sort the frequencies in descending order
  const sortedFreq = Array.from(freqMap.values()).sort((a, b) => b - a);
  
  // return the kth frequency
  return sortedFreq[k - 1];
}
538 chars
18 lines

Here's an example usage of the function:

index.tsx
const arr = [1, 2, 2, 3, 4, 4, 4, 5, 5];
console.log(kthMostCommonElement(arr, 2)); // Output: 3
97 chars
3 lines

In this example, the 2nd most common element in the array [1, 2, 2, 3, 4, 4, 4, 5, 5] is 3. The output of the function call kthMostCommonElement(arr, 2) is 3.

gistlibby LogSnag