'use strict';

const gradesTable = [
  ['Name', 'Mathematics', 'English', 'Biology', 'History'],
  ['Anna', 85, 92, 78, 88],
  ['Ben', 90, 88, 84, 79],
  ['Clara', 76, 95, 89, 91],
  ['David', 82, 79, 91, 85],
];

// Helper: Calculates average of an array of numbers
const getAverage = (numbers) => {
  const sum = numbers.reduce((acc, curr) => acc + curr, 0);
  const avg = sum / numbers.length;
  return Number(avg.toFixed(2));
};

// 1. Calculate average per student
const calculateAvgGrades = (table) => {
  // We take the rows (excluding header), and map each row to a single average value
  return table.slice(1).map((row) => {
    const grades = row.slice(1); // Remove student name
    return getAverage(grades);
  });
};

// 2. Calculate average per subject
const calculateAvgSubjects = (table) => {
  const headers = table[0].slice(1); // Get subject names ['Mathematics', 'English', ...]
  const rows = table.slice(1); // Get data rows

  // We map over the headers to create a result for each subject column
  return headers.map((_, colIndex) => {
    // For the current column, extract the value from every row
    // Note: colIndex starts at 0, but in the row data, grades start at index 1
    const columnGrades = rows.map((row) => row[colIndex + 1]);
    return getAverage(columnGrades);
  });
};

// Tests
console.log('Student Averages:', calculateAvgGrades(gradesTable));
// Expected: [85.75, 85.25, 87.75, 84.25]

console.log('Subject Averages:', calculateAvgSubjects(gradesTable));
// Expected: [83.25, 88.50, 85.50, 85.75]
