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.tsx244 chars11 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.tsx34 chars2 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