Sort and Find Marks Deliberately
Sort and Find Marks Deliberately
The default array sort compares string representations. A numeric comparator is necessary for a school mark list, and copying first avoids rearranging the original class record.
Before this topic, review Use Keyed and Unique Collections if its terms are unfamiliar.
What you’ll learn
- Explain sort and find marks deliberately through the school example.
- Trace the shown operations and distinguish their result from displayed output.
- Make the practice change and explain its consequence: Reversing the numeric comparator sorts descending while preserving the original array.
Work through the school example
This is JavaScript using language features and the host console. Read the initial values, then follow each operation to its displayed result. A declaration names a value, a function call performs an operation, and console.log displays its arguments.
JavaScript · school.js · complete example
const marks = [9, 80, 100];
const sorted = [...marks].sort((a, b) => a - b);
console.log(sorted.join(","));
console.log(marks.join(","));
Expected output
9,80,100
9,80,100Run in JavaScript compiler →Recognize the important boundary
sort mutates its receiver. Comparators should behave consistently; a copied outer array still shares any nested student objects.
Try a small variation
JavaScript · original source for practice
const marks = [9, 80, 100];
const sorted = [...marks].sort((a, b) => a - b);
console.log(sorted.join(","));
console.log(marks.join(","));
Your task: Replace a - b with b - a. Predict the result before running the edited program.
The source is repeated here. If the edit targets the HTML rather than the script, use the markup repeated below; the worked answer also repeats the changed markup.
Worked answer and reasoning
Reversing the numeric comparator sorts descending while preserving the original array.
JavaScript · complete worked variation
const marks = [9, 80, 100];
const sorted = [...marks].sort((a, b) => b - a);
console.log(sorted.join(","));
console.log(marks.join(","));
Expected output
100,80,9
9,80,100Run in JavaScript compiler →Predict the original program
JavaScript · original program for this question
const marks = [9, 80, 100];
const sorted = [...marks].sort((a, b) => a - b);
console.log(sorted.join(","));
console.log(marks.join(","));
Keep the useful idea
The default array sort compares string representations. A numeric comparator is necessary for a school mark list, and copying first avoids rearranging the original class record.
Check your variation against this explanation: Reversing the numeric comparator sorts descending while preserving the original array.
Use the JavaScript array reference library for individual array operations and boundary tests to check a rule independently.
Reaching the recap and completing the quizzes are separate milestones.