Skip to content

Przemysław Konieczniak - Dev Notes

Sorting quirks

JavaScript

What will be result of the below operation?

[1, 10, 2, 5, 11].sort()

Yes, you are right the output will be the same as the input. If you are surprised of the sorting result here is a short explanation.

arr.sort([compareFunction])

compareFunction | Optional

Specifies a function that defines the sort order. If omitted, the array elements are converted to strings, then sorted according to each character's Unicode code point value.

According to the definition we already understand how the default sorting works.

[1, 2, 3, 1, 2, 3].sort() -> [1, 1, 2, 2, 3, 3]

The above sorting works as we expected. The Unicode point value of digit 1 is smaller than 2 and so on.

Richer of this knowledge lets try to answer how will be the result of this sorting.

1) ['a', 'B', 'A', 'b'].sort()
2) ['d', 'b', 'c', 'a'].sort()
3) ['a', 'b', 1, 'A'].sort()
1) ['A', 'B', 'a', 'b'] -> Capital letters are before the small letters
2) ['a', 'b', 'c', 'd'] -> Small letters are sorted correctly
3) [1, 'A', 'a', 'b'] -> Digits are before the letters in the Unicode

Also, keep in mind that the sort method is an impure function and mutates the array.

const arr = ['foo', 'bar', 'baz']
arr.sort()
console.log(arr) -> ['bar', 'baz', 'foo']
© 2020 by Przemysław Konieczniak - Dev Notes. All rights reserved.