calculate the mean by group in javascript

One way to calculate the mean by group in JavaScript is to use the reduce method on an array of objects. Assuming we have an array of objects with a "group" property and a "value" property, we can group the objects by their "group" property and calculate the mean for each group using reduce.

Here is an example code snippet:

index.tsx
// Example array of objects
const data = [
  { group: 'A', value: 10 },
  { group: 'B', value: 15 },
  { group: 'B', value: 20 },
  { group: 'A', value: 5 },
  { group: 'C', value: 8 }
];

// Group and calculate mean with reduce
const groupedMean = data.reduce((acc, {group, value}) => {
  if (!acc[group]) {
    acc[group] = { sum: 0, count: 0 };
  }
  acc[group].sum += value;
  acc[group].count++;
  return acc;
}, {});

Object.keys(groupedMean).forEach(group => {
  const mean = groupedMean[group].sum / groupedMean[group].count;
  console.log(`Group ${group} Mean: ${mean}`);
});
585 chars
24 lines

In this example, we first define an array of objects called "data" with a "group" and "value" property. We then use the reduce method to loop through the array and group the objects by their "group" property. For each group, we keep track of the sum of the values and the count of the number of objects. Finally, we calculate the mean for each group by dividing the sum by the count and log the result to the console.

gistlibby LogSnag