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.tsx238 chars11 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