从JavaScript数组派生计算数据技术求助
Got it, let's walk through how to pull all sorts of useful derived data from your students array. I’ll cover common use cases with practical JavaScript examples that you can adapt to your needs.
You’ll often need to narrow down the array to students who meet specific conditions. Here are some common filters:
Get students who are both athletes and honors students
const athleteHonorsStudents = students.filter(student => student.isAthlete && student.isHonors);Get non-athlete, non-honors students
const regularStudents = students.filter(student => !student.isAthlete && !student.isHonors);Get students with test scores above a threshold (e.g., 85)
const highScorers = students.filter(student => student.testScore > 85);
Use reduce() to compute aggregate values across the array:
Calculate the average test score
const totalScore = students.reduce((sum, student) => sum + student.testScore, 0); const averageScore = totalScore / students.length; console.log(`Average score: ${averageScore.toFixed(2)}`); // Rounds to 2 decimal placesCount students in each category
const studentCounts = students.reduce((counts, student) => { if (student.isAthlete && student.isHonors) counts.athleteHonors++; else if (student.isAthlete) counts.athletes++; else if (student.isHonors) counts.honors++; else counts.regular++; return counts; }, { athleteHonors: 0, athletes: 0, honors: 0, regular: 0 });Find the highest and lowest test scores
const scores = students.map(student => student.testScore); const highestScore = Math.max(...scores); const lowestScore = Math.min(...scores);
Sort the array (create a copy first to avoid modifying the original):
Sort by test score (highest to lowest)
const sortedByScoreDesc = [...students].sort((a, b) => b.testScore - a.testScore);Sort by student name (alphabetical order)
const sortedByName = [...students].sort((a, b) => a.studentName.localeCompare(b.studentName));
Convert the array into a more useful format for lookups or display:
Create a student ID-to-name mapping
const idToNameMap = students.reduce((map, student) => { map[student.studentId] = student.studentName; return map; }, {}); // Use like: idToNameMap['sss1'] → 'Bobby'Generate a simplified array of student names and scores
const studentScoreSummary = students.map(student => ({ name: student.studentName, score: student.testScore }));
If you have a specific derived data point in mind (like weighted scores, or passing rates for a subset), just let me know and I can tweak these examples!
内容的提问来源于stack exchange,提问作者Clay_F

