Comparators & mutation
Sort with an explicit rule
Lesson 16 of 20 · 12 min · Module 5: Reliable data pipelines
Sorting changes the order in which a person encounters information. The order should follow a clear rule and preserve data owned by the caller.
Start this lesson →Free. No installation: you write and run the code in your browser, and it is checked automatically.
By the end, you’ll be able to…
- Write numeric and tie-breaking comparisons
- Protect the caller’s array order
The idea
JavaScript’s sort() changes its array in place. Make an array copy first. Return a negative, zero, or positive number from the comparator to describe the relative order.
const values = [10, 2, 30];
const ordered = [...values].sort((a, b) => a - b);
console.log(ordered);
01Understand the default
Without a comparator, sort compares string forms. That is why numeric values like 10 and 2 need an explicit numeric comparison.
02Return an ordering relationship
a.minutes - b.minutes is negative when a is shorter. A zero difference lets you move to the title rule.
03Separate array and object copying
This function changes only ordering, so copying the array is enough. It does not edit the session objects inside the array.
Your turn
shortestFirst(sessions). Return a new array sorted by minutes ascending, then title ascending for equal durations. Titles use ordinary ASCII letters. Do not reorder the original array.What the checks look for
- Sorts numerically rather than as text
- Uses titles to break a duration tie
- Leaves the original order unchanged
- Accepts an empty list
Take this with you
An explicit comparator makes ordering deliberate and testable.
Go a little further
Add descending order as an optional argument while preserving the same tie rule.