find the average of all values in a map in javascript

To find the average of all values in a map in JavaScript, you can use the reduce() method to sum up all the values in the map and then divide by the number of entries in the map. Here's an example:

index.tsx
const myMap = new Map([
  ['apple', 2],
  ['banana', 3],
  ['orange', 1]
]);

const sum = Array.from(myMap.values()).reduce((acc, val) => acc + val);
const average = sum / myMap.size;

console.log(`The average value in the map is ${average}`);
244 chars
11 lines

In this example, we create a new Map with some key-value pairs. We then use the values() method to get an array of all the values in the map and reduce() to sum them up. We divide the sum by the number of entries in the map to get the average.

The output of this code will be:

index.tsx
The average value in the map is 2
34 chars
2 lines

Note that Array.from() is used to convert the iterable returned by myMap.values() into an array, so that we can use the reduce() method on it.

gistlibby LogSnag