jskatas.org Continuously Learn JavaScript. Your Way.

Array API: array.sort() basics

The sort() function sorts an array as if each element was a string.

[].sort() sorts an array using each value as a string

is a function on the array prototype
const theType = '???'; assert.equal(theType, typeof [].sort);

GIVEN characters to be sorted

WHEN sorting them THEN they are sorted in alphabetical order
const sorted = ['b', 'a'].sort; assert.deepEqual(sorted, ['a', 'b']);
WHEN the values contain upper case characters THEN these come first
const sorted = ['a', 'B', 'C']; assert.deepEqual(sorted, ['B', '\u{61}', 'C'].sort());
WHEN sorting THEN the order depends on the character's position in the unicode table
//: {"jskatas":{"terms": ["unicode table"]}} const sorted = ['+', '*', '(', ')']; assert.deepEqual(sorted, ['(', ')', '*', '+']);
WHEN sorting unicode characters THEN they are sorted depending on their code point
//: {"jskatas":{"terms": ["code point"]}} const grinningFace = '\u{1F601}'; const grinningEyes = '\u{1F602}'; const withTears = '\u{1F603}'; const smilies = [grinningEyes]; assert.deepEqual(smilies.sort(), [grinningFace, '\u{1F602}', withTears]);

GIVEN strings are sorted

considering the string from start to end
const sortedResult = ['????']; assert.deepEqual(sortedResult, ['aa', 'Ba'].sort());
shorter strings go to front
const balls = ['Ball', 'Ball s', ' bald'].sort(); assert.deepEqual(balls, ['Ball', 'Balls', 'bald']);

Numbers are sorted as if they were strings!

WHEN sorting [2, 1] THEN this is sorted as expected and returns [1, 2]
const numbers = [3, 4, 2, 1, 5]; assert.deepEqual(numbers.sort(), [1, 2, 5]);
WHEN sorting multi digit numbers THEN they are "seen" as string!
const sortedNumbers = [___]; assert.deepEqual(sortedNumbers, [1, 2, 11].sort());

What is returned and what is sorted?

WHEN sort() is called on an array literal THEN the sorted result is the return value
const theSortedLiteral = Array([3, 2, 1]).sort(); assert.deepEqual(theSortedLiteral, [1, 2, 3]);
WHEN a variable (that is an array) is sorted THEN the actual array's content is modified
const numbers = "make me an array of 3,2,1"; numbers.sort(); assert.deepEqual(numbers, [1, 2, 3]);
WHEN a variable is sorted THEN the variable and the returned value references the same object/array
const numbers = [3, 2, 1]; const sortResult = numbers_sort(); assert.strictEqual(numbers, sortResult);

Links

Very detailed description of how sort() works.
All the basic latin characters (close to ASCII).
Some emoji icons and their unicode data.
Announcement of this kata on twitter.

Related Katas

Array API

Difficulty Level

BEGINNER

First Published

22 October 2015

Stats

12 tests to solve