find the mode of all keys in a map in typescript

To find the mode, or the most frequently occurring key, in a map in TypeScript, we can follow these steps:

  1. Convert the keys of the map to an array using the keys() method and spread operator.
  2. Create another array to hold the frequency counts of each key.
  3. Iterate through the array of keys and count the frequency of each key by iterating through the remaining keys in the array and incrementing the frequency counter for that key.
  4. Find the maximum frequency count in the frequency array.
  5. Return the key corresponding to the maximum frequency count.

Here's the code:

index.ts
function findMode(map: Map<any, any>): any {
  const keysArray = [...map.keys()]; // Step 1
  const freqArray = [];

  for (let i = 0; i < keysArray.length; i++) {
    let count = 0;

    for (let j = i; j < keysArray.length; j++) {
      if (keysArray[i] === keysArray[j]) {
        count++;
      }
    }

    freqArray.push(count); // Step 2 and 3
  }

  const maxFreq = Math.max(...freqArray); // Step 4
  const modeIndex = freqArray.indexOf(maxFreq);

  return keysArray[modeIndex]; // Step 5
}
500 chars
22 lines

This function takes in a map and returns the mode key. If there are multiple keys with the same maximum frequency count, this function will return the first one encountered in the keys array.

gistlibby LogSnag