This commit is contained in:
Philippe Torrel
2026-07-07 10:29:34 +02:00
parent f3ca79e09b
commit f583bf92a3
14 changed files with 201 additions and 61 deletions

View File

@@ -0,0 +1,80 @@
<!doctype html>
<html lang="de">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Übung 14: Durchschnittsnoten berechnen</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<main>
<div class="container py-5">
<div class="alert alert-primary">
<h2>Übung 14: Durchschnittsnoten berechnen</h2>
<p>
Durchschnitt pro Schüler (<strong>calculateAvgGrades</strong>): Schreibe eine Funktion, die die
Durchschnittsnote jedes Schülers (zeilenweise) berechnet. Das Ergebnis soll ein Array mit den
Durchschnittswerten der Schüler (Anna, Ben, Clara, David) sein.
</p>
<p>
Durchschnitt pro Fach (<strong>calculateAvgSubjects</strong>): Schreibe eine Funktion, die die
Durchschnittsnote jedes Fachs (spaltenweise) berechnet. Das Ergebnis soll ein Array mit den
Durchschnittswerten der Fächer (Mathematics, English, Biology, History) sein.
</p>
<div class="output alert alert-secondary my-3"></div>
</div>
</div>
</main>
<script>
'use strict';
const outputEl = document.querySelector('.output');
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],
];
const calculateAverageGrades = (ar = []) => {
return ar.slice(1).map((row) => {
const grades = row.slice(1); // => [85, 92, 78, 88]
const avgGrades = grades.reduce((a, b) => a + b, 0) / grades.length;
return Number(avgGrades.toFixed(2));
});
};
// [].reduce((INDEX_A, INDEX_B) => {}, INITIAL_VALUE)
console.log(
[85, 92, 78, 88].reduce((sum, n) => {
return Number(sum) + Number(n);
}, 0),
); // => 343
const calculateAvgSubjects = (ar = []) => {
const entries = ar.slice(1);
const grades = entries.map((ar) => ar.slice(1));
console.log(grades);
// [
// []
// [85, 92, 78, 88]
// [90, 88, 84, 79]
// [76, 95, 89, 91]
// [82, 79, 91, 85]
// ]
const results = grades.reduce((resAr, nAr) => {
resAr.push(nAr[0]);
return resAr;
}, []);
console.log(results);
};
console.log(calculateAvgSubjects(gradesTable));
console.log(calculateAverageGrades(gradesTable));
outputEl.textContent = `Average grades of students are: ${calculateAverageGrades().join(' - ')}`;
</script>
</body>
</html>