Author Topic: array.sort() with no function argument?  (Read 4025 times)

Offline mschuster

  • PTeam Member
  • PixInsight Jedi
  • *****
  • Posts: 1087
array.sort() with no function argument?
« on: 2014 December 15 21:34:37 »
Hi Juan,

Win 7, 1123:

Calling array.sort() with no function argument on a short array modifies the array, but the result is not "sorted".

Is this a problem? I thought previous versions defaulted to a low to high sort?

Using an explicit compare function gives good results.

Mike

Code: [Select]
array:
0.533087,-1.02232,-0.855217

array.sort():
-0.855217,-1.02232,0.533087

array.sort(sortCompare):
-1.02232,-0.855217,0.533087

Code: [Select]
var array = [0.533087, -1.02232, -0.855217];
console.writeln("\narray:");
console.writeln(array);

var array = [0.533087, -1.02232, -0.855217];
array.sort();
console.writeln("\narray.sort():"); // ? bug
console.writeln(array);

function sortCompare(a, b) {
   return a < b ? -1 : a > b ? 1 : 0;
}

var array = [0.533087, -1.02232, -0.855217];
array.sort(sortCompare);
console.writeln("\narray.sort(sortCompare):");
console.writeln(array);

Offline Juan Conejero

  • PTeam Member
  • PixInsight Jedi Grand Master
  • ********
  • Posts: 7111
    • http://pixinsight.com/
Re: array.sort() with no function argument?
« Reply #1 on: 2014 December 16 01:13:42 »
Hi Mike,

Not a bug, just the way Array.sort() is defined by the ECMA specification. Array elements are sorted by Unicode code points after applying Object.toString() to each element. See for example:

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

So  "-0.855217" precedes "-1.02232" because "0" precedes "1". The sort is always correct for an array of positive values but *not* if there are negative values. In practice, this means that we always have to use a comparison function in these cases.
Juan Conejero
PixInsight Development Team
http://pixinsight.com/