JavaScriptFundamental (ES6), part 1
Sort by multiple fields in JavaScript
98 a comparator factory, and sorting by several keys
fairWrite byKey(key, direction) that returns a comparator, and then(...comparators) that runs them in order until one of them cares. Sort a list of market stalls by market ascending then takings descending. Then show why a - b and a boolean-returning comparator are both wrong more often than they look.
Stuck? Three hints, smallest first
- 1. A comparator answers one question with three possible answers: negative, zero, positive. Nothing else.
- 2.
(x < y ? -1 : x > y ? 1 : 0)works for numbers and strings alike, and multiplying it by-1is the whole of descending. - 3.
thenloops over the comparators and returns the first non-zero answer. Returning0at the end is what keeps the sort stable.
const byKey = (key, direction = 'asc') => {
const of = typeof key === 'function' ? key : (item) => item[key];
const sign = direction === 'desc' ? -1 : 1;
return (a, b) => {
const x = of(a);
const y = of(b);
return (x < y ? -1 : x > y ? 1 : 0) * sign;
};
};
const then = (...comparators) => (a, b) => {
for (const compare of comparators) {
const answer = compare(a, b);
if (answer !== 0) return answer;
}
return 0;
};
const stalls = [
{ stall: 'A12', market: 'Balogun', takings: 12000 },
{ stall: 'B03', market: 'Alaba', takings: 30000 },
{ stall: 'A07', market: 'Balogun', takings: 30000 },
{ stall: 'C21', market: 'Alaba', takings: 9000 },
];
const ids = (list) => list.map((s) => s.stall);
const byTakings = ids([...stalls].sort(byKey('takings')));
const byTakingsDesc = ids([...stalls].sort(byKey('takings', 'desc')));
const grouped = ids([...stalls].sort(then(byKey('market'), byKey('takings', 'desc'))));
const byNameLength = ids([...stalls].sort(byKey((s) => s.market.length)));
const inPlace = [...stalls];
const returnedSame = inPlace.sort(byKey('takings')) === inPlace;
const originalUntouched = stalls[0].stall;
const asText = [10, 9, 100].sort();
const codeUnits = ['ada', 'Zainab', 'bola'].sort(byKey((s) => s));
const withLocale = ['ada', 'Zainab', 'bola'].sort((a, b) => a.localeCompare(b, 'en'));
const boolish = (a, b) => a > b;
const bothWays = [Number(boolish(1, 2)), Number(boolish(2, 1))];
const subtractive = (a, b) => a - b;
const onStrings = subtractive('bola', 'ada');
console.log('takings :', byTakings, '| desc:', byTakingsDesc);
console.log('grouped :', grouped);
console.log('default :', asText, '| code units:', codeUnits, '| locale:', withLocale);
console.log('boolean :', bothWays, '| subtraction on text:', onStrings);
Output
9 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 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('one key, ascending, ties left in their input order', byTakings, ['C21', 'A12', 'B03', 'A07']);
test('desc is the same comparator times minus one', byTakingsDesc, ['B03', 'A07', 'A12', 'C21']);
test('then runs the comparators until one of them cares', grouped, ['B03', 'C21', 'A07', 'A12']);
test('the key can be computed, not just named', byNameLength, ['B03', 'C21', 'A12', 'A07']);
test('sort mutates and returns the array it was given, so copy first', [returnedSame, originalUntouched], [true, 'A12']);
test('with no comparator, sort compares the string forms', asText, [10, 100, 9]);
test('comparing strings with < is code-unit order, which puts capitals first', [codeUnits, withLocale], [['Zainab', 'ada', 'bola'], ['ada', 'bola', 'Zainab']]);
test('a boolean comparator can only say two things, and "before" is not one of them', bothWays, [0, 1]);
test('subtraction only compares numbers; on text it produces NaN', Number.isNaN(onStrings), true);
A comparator is a function of two items returning a sign, and every sorting problem in JavaScript reduces to building the right one. Making it a factory rather than writing the arrow inline is what lets you compose: then(byKey('market'), byKey('takings', 'desc')) reads like the sentence you would say out loud, and adding a third key costs nothing.
The default comparator catches everyone once. [10, 9, 100].sort() gives [10, 100, 9], because with no function the spec converts each element to a string and compares those. There is no numeric mode; you always pass a comparator for numbers.
Three failures worth remembering. a - b is fine for finite numbers and produces NaN for anything else, and a NaN comparator makes the result unspecified rather than throwing. A boolean comparator is worse: true becomes 1 and false becomes 0, so it can say "after" and "same" but never "before", and the sort quietly half-works. And < on strings compares UTF-16 code units, so every capital letter sorts before every lowercase one and accented names land past z; when the order will be read by a person, localeCompare is the comparator you want.