find the median of all values in a map in javascript

Assuming the values in your map are numerical, you can use the following code to find the median:

index.tsx
const mapValues = myMap.values(); // get all the values of the map
const sortedValues = [...mapValues].sort((a, b) => a - b); // sort the values in ascending order

if (sortedValues.length % 2 === 0) { // if there are an even number of values
  const midIndex = sortedValues.length / 2;
  const median = (sortedValues[midIndex - 1] + sortedValues[midIndex]) / 2;
  console.log(median);
} else { // if there are an odd number of values
  const midIndex = Math.floor(sortedValues.length / 2);
  const median = sortedValues[midIndex];
  console.log(median);
}
557 chars
13 lines

Explanation:

  • myMap.values() returns an iterator for all the values in the map
  • ...mapValues spreads the iterator into an array so we can sort the values
  • sort((a, b) => a - b) sorts the values in ascending order
  • sortedValues.length % 2 === 0 checks if there are an even number of values
  • If there are an even number of values, we take the two middle values and calculate their average to get the median
  • If there are an odd number of values, we take the middle value as the median.

gistlibby LogSnag