find the mode of all values in a map in javascript

To find the mode (most frequent value) in a JavaScript map or object, we need to iterate over all the key-value pairs and track the frequency of each value. Here's one way to do it:

index.tsx
function findMode(map) {
  let maxFreq = 0;
  let mode;

  // create a frequency table
  const freq = {};

  // iterate over each value in the map
  map.forEach(value => {
    // increase the frequency count for this value
    freq[value] = (freq[value] || 0) + 1;

    // check if this value has a higher frequency than the current mode
    if (freq[value] > maxFreq) {
      maxFreq = freq[value];
      mode = value;
    }
  });

  return mode;
}
450 chars
22 lines

This function takes a map as input and returns the mode value. It works by creating a frequency table (an object where the keys are the values in the original map, and the values are the frequency counts of each value). Then, it iterates over the map and updates the frequency count for each value. Finally, it checks if the current value has a higher frequency than the current mode, and updates the mode if necessary.

Here's an example usage of the findMode function:

index.tsx
const myMap = new Map([
  ['a', 1],
  ['b', 2],
  ['c', 2],
  ['d', 3],
  ['e', 3],
  ['f', 3],
]);

const mode = findMode(myMap);
console.log(mode); // output: '3'
165 chars
12 lines

In this example, the mode value is '3', since it appears three times in the map (the values 'd', 'e', and 'f').

gistlibby LogSnag