find the variance of all keys in a map in javascript

To find the variance of all keys in a map in JavaScript, we first need to extract the values of the map into an array. We can do this using the Array.from() method.

Once we have an array of values, we can use the reduce() method to calculate the average of all keys. Finally, we can loop through the array of values and calculate the variance by subtracting the average from each value, squaring the result and then adding up all the squared differences. Dividing this sum by the length of the array minus one gives us the variance of all keys.

Here's the code to achieve this:

index.tsx
const myMap = new Map([
  ['key1', 10],
  ['key2', 5],
  ['key3', 15],
  ['key4', 20],
  ['key5', 25]
]);

const valuesArray = Array.from(myMap.values());

const avg = valuesArray.reduce((acc, val) => acc + val, 0) / valuesArray.length;

const variance = valuesArray.reduce((acc, val) => {
  const diff = val - avg;
  return acc + (diff * diff);
}, 0) / (valuesArray.length - 1);

console.log(variance);
404 chars
19 lines

gistlibby LogSnag