2

Today working with task on JS I found that JavaScript out of the box have powerful comparison of arrays:

console.log(["a","b"] > ["a","aa"] && ['a','aa'] < ['a', 'cc']) // true

This leads to shortcut sorting for two dimensional arrays with strings

console.log([["a","aa"],['b','bb'],["a","c"],['b',"ab"],['b',"a"]].sort())
/*
[ [ 'a', 'aa' ],
  [ 'a', 'c' ],
  [ 'b', 'a' ],
  [ 'b', 'ab' ],
  [ 'b', 'bb' ] ]*/

JavaScript automatically order sub arrays with similar first element. Now I'm seek for formal definition how do JavaScript compares two arrays.

3

2 Answers 2

3

By taking Array#sort, you get the following Description to the use of the parameter compareFunction:

If compareFunction is not supplied, all non-undefined array elements are sorted by converting them to strings and comparing strings in UTF-16 code units order. For example, "banana" comes before "cherry". In a numeric sort, 9 comes before 80, but because numbers are converted to strings, "80" comes before "9" in Unicode order. All undefined elements are sorted to the end of the array.

The result is an array which looks like sorted, at least for the first element unless the elements contains commas.

Sign up to request clarification or add additional context in comments.

Comments

1

The sort() method sorts the elements of an array in place and returns the array. The default sort order is built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.

See Array.prototype.sort()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.