JavaScriptFundamental (ES6), part 2
Sort with a pinned item and tie-breaker in JavaScript
83 A sort with one row pinned and ties broken by a second key
fairRank riders by deliveries, highest first, breaking ties by name A to Z — and keep one chosen rider pinned to the top whatever his numbers say. Leave the caller's array alone. Then look at why the comparator returns numbers rather than booleans.
Stuck? Three hints, smallest first
- 1. A comparator can be several comparisons joined with
||, because a tie returns0and0is falsy. - 2. Turn "is this the pinned row" into a number —
0for pinned,1for not — and subtract. - 3.
sortsorts in place and returns the same array, so copy with[...rows]first.
const riders = [
{ id: 'R1', name: 'Chinedu', deliveries: 41 },
{ id: 'R2', name: 'Bukola', deliveries: 12 },
{ id: 'R3', name: 'Amaka', deliveries: 63 },
{ id: 'R4', name: 'Zainab', deliveries: 41 },
{ id: 'R5', name: 'Tunde', deliveries: 63 },
];
const compareRiders = (pinnedId) => (a, b) =>
(a.id === pinnedId ? 0 : 1) - (b.id === pinnedId ? 0 : 1) || // pinned row first
b.deliveries - a.deliveries || // then deliveries, descending
a.name.localeCompare(b.name); // then name, A to Z
const rank = (rows, pinnedId) => [...rows].sort(compareRiders(pinnedId));
const names = (rows) => rows.map((r) => r.name);
const withPin = rank(riders, 'R2');
const withoutPin = rank(riders);
const pinNotPresent = rank(riders, 'R99');
const originalUntouched = names(riders);
const pinnedBeatsEverything = compareRiders('R2')(riders[1], riders[2]) < 0;
const identicalRows = compareRiders(null)({ id: 'x', name: 'Amaka', deliveries: 63 }, riders[2]);
const booleanComparator = [riders[1].deliveries > riders[2].deliveries, Number(riders[1].deliveries > riders[2].deliveries)];
console.log('pinned R2 :', names(withPin));
console.log('unpinned :', names(withoutPin));
console.log('original :', originalUntouched, '<- still as written');
Output
8 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('the pinned rider is first even with the fewest deliveries', names(withPin), ['Bukola', 'Amaka', 'Tunde', 'Chinedu', 'Zainab']);
test('and the comparator says so directly', pinnedBeatsEverything, true);
test('without a pin it is deliveries descending', names(withoutPin).slice(0, 2), ['Amaka', 'Tunde']);
test('ties are broken by name, so Amaka precedes Tunde and Chinedu precedes Zainab', names(withoutPin), ['Amaka', 'Tunde', 'Chinedu', 'Zainab', 'Bukola']);
test('pinning an id that is not in the list changes nothing', names(pinNotPresent), names(withoutPin));
test('the caller\'s array was not reordered, because we copied before sorting', originalUntouched, ['Chinedu', 'Bukola', 'Amaka', 'Zainab', 'Tunde']);
test('two rows equal on every key compare as 0, which is what lets || fall through', identicalRows, 0);
test('a boolean comparator can only ever say "equal" or "after"', booleanComparator, [false, 0]);
The || chain is the whole technique. Each comparison returns a negative number, a positive number, or 0 for a tie, and 0 is the only falsy one, so || moves to the next key exactly when the current one cannot decide. Adding a third tie-break is one more line, and no nesting appears.
Pinning is done as arithmetic on purpose. (a.id === pin ? 0 : 1) - (b.id === pin ? 0 : 1) gives -1, 1 or 0, and the 0 case — neither row is pinned — falls through to the real ranking. The tempting version, if (a.id === pin) return -1;, is subtly broken: it claims the pinned row sorts before itself, which is an inconsistent comparator, and inconsistent comparators produce implementation-defined orders rather than errors.
The last assertion is why comparators return numbers. a > b gives true or false, which coerce to 1 and 0 — there is no way to express "a comes first", so half the information the sort needs never arrives. The result is not random, it is engine-specific, which is worse: it passes in one browser and reorders rows in another. sort mutating in place is the other half of the sixth assertion. It returns the same array it was handed, so const sorted = rows.sort(...) silently reorders the caller's data and hands back an alias, not a copy.