// 定义各科评分规则 (可动态配置)
const subjectConfig = {
语文: { total: 150, pass: 90, high: 120 },
数学: { total: 150, pass: 90, high: 135 },
英语: { total: 120, pass: 72, high: 108 },
化学: { total: 100, pass: 60, high: 85 },
物理: { total: 100, pass: 60, high: 85 },
历史: { total: 100, pass: 60, high: 85 },
道法: { total: 100, pass: 60, high: 85 }
};
// 核心统计函数 (支持动态科目和规则)
function analyzeResults(students, subjectConfig) {
const subjects = Object.keys(subjectConfig);
// 初始化班级统计结构: Map<班级标识, 统计对象>
const classStats = new Map();
const globalStats = {
total: 0,
passAll: 0,
highAny: 0,
subjects: subjects.reduce((acc, subject) => ({
...acc,
[subject]: { pass: 0, high: 0 }
}), {})
};
// 遍历学生数据
students.forEach(student => {
// 生成班级唯一标识 (年级+班级)
const classKey = `${student.年级}_${student.班级}`;
// 动态初始化班级统计
if (!classStats.has(classKey)) {
classStats.set(classKey, {
total: 0,
passAll: 0,
highAny: 0,
subjects: subjects.reduce((acc, subject) => ({
...acc,
[subject]: { pass: 0, high: 0 }
}), {})
});
}
const clsStats = classStats.get(classKey);
// 更新计数
clsStats.total++;
globalStats.total++;
// 核心判断逻辑
let isAllPassed = true;
let hasAnyHigh = false;
subjects.forEach(subject => {
const { pass, high } = subjectConfig[subject];
const score = student[subject];
// 判断单科是否及格
const isPass = score >= pass;
if (isPass) {
clsStats.subjects[subject].pass++;
globalStats.subjects[subject].pass++;
} else {
isAllPassed = false; // 存在一科不及格则全科不通过
}
// 判断单科是否高分
const isHigh = score >= high;
if (isHigh) {
clsStats.subjects[subject].high++;
globalStats.subjects[subject].high++;
hasAnyHigh = true;
}
});
// 更新全科/高分统计
if (isAllPassed) {
clsStats.passAll++;
globalStats.passAll++;
}
if (hasAnyHigh) {
clsStats.highAny++;
globalStats.highAny++;
}
});
// 计算比率
const calculateRates = (stats) => ({
...stats,
passAllRate: (stats.passAll / stats.total).toFixed(4),
highAnyRate: (stats.highAny / stats.total).toFixed(4),
subjects: Object.entries(stats.subjects).reduce((acc, [subject, data]) => ({
...acc,
[subject]: {
passRate: (data.pass / stats.total).toFixed(4),
highRate: (data.high / stats.total).toFixed(4)
}
}), {})
});
// 生成最终结构化数据
return {
byClass: Object.fromEntries(
Array.from(classStats).map(([classKey, stats]) => [
classKey,
{ ...calculateRates(stats), total: stats.total }
])
),
global: {
...calculateRates(globalStats),
total: globalStats.total,
subjects: Object.entries(globalStats.subjects).reduce((acc, [subject, data]) => ({
...acc,
[subject]: {
pass: data.pass,
passRate: (data.pass / globalStats.total).toFixed(4),
high: data.high,
highRate: (data.high / globalStats.total).toFixed(4)
}
}), {})
}
};
}
// 使用示例
const result = analyzeResults(students, subjectConfig);
console.log(result);