Dev Helpers
← Back

Calculate a mean reading for each hour

Calculate a mean reading for each hour. Inspect the transformed data in the console.

Open this example in the interactive library

Source code

const rows = [
  { site: "N", hour: 8, value: 12 },
  { site: "S", hour: 8, value: 17 },
  { site: "N", hour: 9, value: 15 },
  { site: "S", hour: 9, value: 14 },
];
const result = Object.fromEntries(
  [...new Set(rows.map((r) => r.hour))].map((h) => {
    const a = rows.filter((r) => r.hour === h);
    return [h, a.reduce((s, r) => s + r.value, 0) / a.length];
  }),
);
console.log(JSON.stringify(result, null, 2));

Sample output

{
  "8": 14.5,
  "9": 14.5
}