CodexBloom - Programming Q&A Platform

Sorting Nested Arrays in JavaScript - Inconsistent Order with Complex Objects

👀 Views: 22 đŸ’Ŧ Answers: 1 📅 Created: 2025-08-24
javascript sorting arrays JavaScript

I'm sure I'm missing something obvious here, but I'm trying to sort an array of student objects based on their grades, which are nested within another array of subjects... Each student can have multiple subjects with different grades, and I want to sort the students by their highest grade across all subjects. However, I'm working with issues where the sort order seems inconsistent, and I need to figure out why. Here's the structure of my data: ```javascript const students = [ { name: 'Alice', grades: [{ subject: 'Math', grade: 85 }, { subject: 'English', grade: 92 }] }, { name: 'Bob', grades: [{ subject: 'Math', grade: 78 }, { subject: 'English', grade: 88 }] }, { name: 'Charlie', grades: [{ subject: 'Math', grade: 95 }, { subject: 'English', grade: 85 }] } ]; ``` I want to sort this array so that students with the highest grades appear first. I've tried the following approach using `Array.prototype.sort()`: ```javascript students.sort((a, b) => { const maxA = Math.max(...a.grades.map(g => g.grade)); const maxB = Math.max(...b.grades.map(g => g.grade)); return maxB - maxA; }); ``` While this works in most cases, it seems like when two students have the same highest grade, they retain their original order, which is not what I expected. Additionally, I noticed that if two students have the same highest grade, they appear at the end rather than maintaining their original order. I want to implement stable sorting behavior. Am I missing something in my sort function, or is there a better way to achieve this? Any advice would be greatly appreciated! My development environment is macOS. What am I doing wrong? I'm on macOS using the latest version of Javascript. This is my first time working with Javascript 3.11. Any pointers in the right direction?