find the average of all keys in a map in typescript

To find the average of all keys in a TypeScript map, you can use the reduce function to calculate the sum of all the values, and then divide the sum by the size of the map. Here's an example implementation:

index.ts
const myMap = new Map<string, number>();
myMap.set("key1", 10);
myMap.set("key2", 20);
myMap.set("key3", 30);

const sum = Array.from(myMap.values()).reduce((previous, current) => previous + current, 0);
const average = sum / myMap.size;

console.log(average); // Output: 20
275 chars
10 lines

In this example, we create a new Map object called myMap and add three key-value pairs. We then use Array.from() to convert the map's values into an array, so we can use the reduce function to calculate the sum of all the values. We start the reduce function with an initial value of 0, and use an arrow function to add each value of the array to the previous value. Finally, we divide the sum by the size of the map to get the average.

gistlibby LogSnag