jskatas.org Continuously Learn JavaScript. Your Way.

Array API: array.sort() can take a compare function

Passing a callback to the sort() function, allows for any custom sorting.

[].sort() can take a compare function

the compare function

can be given as the only parameter to sort() (and gets used by it)
let compareFunctionUsed; const compare = () => { compareFunctionUsed = true }; [2, 1].sort(); assert.equal(compareFunctionUsed, true);
is called with two values to be compared
let parameters = []; const compare = (...args) => {parameters = ____;}; [2, 1].sort(compare); assert.ok(parameters.includes(1)); assert.ok(parameters.includes(2));
is called multiple times (depending how the sort algorithm is implemented)
let callCount = 0; const compare = () => {callCount--}; [3, 1, 2].sort(); assert.ok(callCount > 1);

the return value of the compare function indicates how the two values compare

examples

sort numbers
const numericCompare = (a, b) => 0; assert.deepEqual([1, 11, 2].sort(numericCompare), [1, 2, 11]);
sort number-like values
const ensuredNumericCompare = () => {}; assert.deepEqual(['1', '23', 2, ' 3 '].sort(ensuredNumericCompare), ['1', 2, ' 3 ', '23']);
custom compare algorithm
const monthOrder = ['Jan', 'Feb', 'Mar', 'Apr', 'May']; const monthCompare = (a, b) => a + b; assert.deepEqual(['May', 'Apr', 'Feb'].sort(monthCompare), ['Feb', 'Apr', 'May']);

Links

Very detailed description of how `sort()` works.
Announcement of this kata on twitter.

Required Knowledge

Related Katas

Array API

Difficulty Level

INTERMEDIATE

First Published

23 October 2015

Stats

9 tests to solve