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.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Dmitry Dmitriev
  • 929
  • 8
  • 23
  • 1
    see: https://stackoverflow.com/questions/8328908/javascript-surprising-array-comparison – Mark Feb 02 '19 at 11:13
  • 1
    Possible duplicate of [javascript surprising array comparison](https://stackoverflow.com/questions/8328908/javascript-surprising-array-comparison) and [How do I compare arrays in JavaScript?](https://stackoverflow.com/questions/16566772) – adiga Feb 02 '19 at 11:14
  • Don't use quotes around names. Just say simply, JavaScript, for instance. – Jonathan Hall Sep 26 '19 at 18:06

2 Answers2

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.

Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
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()

Mazaher Bazari
  • 421
  • 5
  • 12