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);

sorts characters

in alphabetical order
const sorted = ['b', 'a'].sort; assert.deepEqual(sorted, ['a', 'b']);
upper case characters come first
const sorted = ['a', 'B', 'C']; assert.deepEqual(sorted, ['B', '\u{61}', 'C'].sort());
depending on their position in the unicode table
const sorted = ['+', '*', '(', ')']; assert.deepEqual(sorted, ['(', ')', '*', '+']);
unicode characters depending on their 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]);

sorts strings

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']);

sorts numbers as if they were strings

1 and 2 are sorted as expected
const numbers = [3, 4, 2, 1, 5]; assert.deepEqual(numbers.sort(), [1, 2, 5]);
see multi digit numbers as strings!
const sortedNumbers = [___]; assert.deepEqual(sortedNumbers, [1, 2, 11].sort());

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.