find the average of all values in a map in typescript

To find the average of all values in a Map in TypeScript, you can use the reduce function to calculate the sum of all values and then divide by the size of the Map.

Here's an example implementation:

index.ts
const map = new Map<string, number>();
map.set('a', 10);
map.set('b', 20);
map.set('c', 30);

const sum = Array.from(map.values()).reduce((acc, val) => acc + val, 0);
const avg = sum / map.size;

console.log(avg); // Output: 20
228 chars
10 lines

In this example, we first create a new Map with some key-value pairs. We then use the Array.from method to create an array of all values in the Map, which we can then reduce to calculate the sum. Finally, we divide the sum by the size of the Map to get the average value.

Note that we use 0 as the initial value for the reduce function to handle the case where the Map is empty.

gistlibby LogSnag