calculate the z score by group. in javascript

To calculate the z score by group in javascript, you can first group your data by some attribute using Array.reduce().

index.tsx
const data = [
  { group: 'A', value: 10 },
  { group: 'A', value: 20 },
  { group: 'B', value: 30 },
  { group: 'B', value: 40 },
];

const groupedData = data.reduce((acc, curr) => {
  acc[curr.group] = acc[curr.group] || [];
  acc[curr.group].push(curr.value);
  return acc;
}, {});

console.log(groupedData);
// output: { A: [ 10, 20 ], B: [ 30, 40 ] }
356 chars
16 lines

Then, for each group, calculate the mean and standard deviation using Array.reduce() and Math functions.

index.tsx
const groupZScores = {};
for (const group in groupedData) {
  const groupValues = groupedData[group];
  const sum = groupValues.reduce((acc, v) => acc + v, 0);
  const mean = sum / groupValues.length;
  const variance = groupValues.reduce((acc, v) => acc + Math.pow(v - mean, 2), 0) / (groupValues.length - 1);
  const stdDev = Math.sqrt(variance);

  groupZScores[group] = groupValues.map((v) => (v - mean) / stdDev);
}

console.log(groupZScores);
// output: { A: [ -1, 1 ], B: [ -1, 1 ] }
491 chars
14 lines

This will give you an object with group names as keys and an array of z scores as values. The z score for a value x is calculated as (x - mean) / standardDeviation. The z score represents how many standard deviations away from the mean the value is.

gistlibby LogSnag