find the kth most frequent element in an array in javascript

One approach to finding the kth most frequent element in an array in JavaScript is to use a hashmap to count the frequency of each element, sort the hashmap by frequency, and then return the kth element.

Here's an implementation:

index.tsx
function kthMostFrequent(arr, k) {
  // Step 1: Count the frequency of each element using a hashmap
  const countMap = {};
  for (const elem of arr) {
    countMap[elem] = (countMap[elem] || 0) + 1;
  }

  // Step 2: Convert the hashmap to an array of [elem, frequency] tuples
  const countArray = Object.entries(countMap);

  // Step 3: Sort the array by frequency in descending order
  countArray.sort((a, b) => b[1] - a[1]);

  // Step 4: Return the kth element, if it exists
  if (k <= countArray.length) {
    return countArray[k - 1][0];
  } else {
    return undefined;
  }
}
583 chars
21 lines

Here's an example usage:

index.tsx
const arr = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4];
const k = 2;
const kth = kthMostFrequent(arr, k);
console.log(`The ${k}th most frequent element is ${kth}.`); // Output: The 2nd most frequent element is 4.
201 chars
5 lines

Note that this implementation assumes that k <= number of distinct elements in the array. If k > number of distinct elements, undefined will be returned.

gistlibby LogSnag