find the mode of all keys in a map in javascript

To find the mode of all keys in a Map in JavaScript, we can follow these steps:

  1. Create an empty array called valuesArr to store all the values of the Map.
  2. Loop through the Map using the Map.forEach() method and push each value to the valuesArr.
  3. Create an empty object called frequency to store the frequency of each value in the valuesArr.
  4. Loop through the valuesArr and add each value as a key to the frequency object if it doesn't already exist, and increment the value of that key by 1.
  5. Create a variable called maxFreq to store the maximum frequency of any value in the frequency object.
  6. Create an empty array called modes to store all the modes of the values in the valuesArr.
  7. Loop through the frequency object and if the value of any key is equal to maxFreq, push that key to the modes array.
  8. Return the modes array as the result, which contains all the modes of the keys in the Map.

Here's the code:

index.tsx
let myMap = new Map();
myMap.set("a", 1);
myMap.set("b", 2);
myMap.set("c", 2);
myMap.set("d", 3);

function getModes(map) {
  let valuesArr = [];
  map.forEach((value, key) => {
    valuesArr.push(value);
  });

  let frequency = {};
  valuesArr.forEach(value => {
    if (!frequency[value]) {
      frequency[value] = 1;
    } else {
      frequency[value]++;
    }
  });

  let maxFreq = 0;
  for (let key in frequency) {
    if (frequency[key] > maxFreq) {
      maxFreq = frequency[key];
    }
  }

  let modes = [];
  for (let key in frequency) {
    if (frequency[key] === maxFreq) {
      modes.push(key);
    }
  }

  return modes;
}

console.log(getModes(myMap)); // ["2"]
683 chars
40 lines

gistlibby LogSnag