find the average of all keys in a map in javascript

To find the average of all the keys in a map in JavaScript, you can use the reduce method to sum up all the keys, and then divide by the total number of keys:

index.tsx
const myMap = new Map([
  ['key1', 5],
  ['key2', 3],
  ['key3', 10]
]);

const total = Array.from(myMap.keys()).reduce((acc, key) => acc + key, 0);
const average = total / myMap.size;

console.log(average); // Output: 2.6666666666666665
238 chars
11 lines

In this example, we first create a new Map object called myMap with some key-value pairs. We then convert the keys of the map into an array using Array.from, and use reduce to sum up all the keys. Finally, we divide the sum by the total number of keys in the map to get the average.

Note that the result of the calculation is a float with a long fractional part because the keys of the map are all strings. If you want to get the average as an integer or a rounded float, you can use the Math.floor, Math.ceil, or Math.round functions to convert the result as desired.

gistlibby LogSnag