array.sort() compare function weirdness in ExtendScript
I'm posting this in InDesign Scripting forum, since I encountered the problem while working on a script for InDesign CC 2015, but it seems to concern the whole of ExtendScript.
In my script, I'm using the array.sort() method with a custom compare function in order to sort an array of objects with respect to one of their properties. I will present a generalized version of the relevant part so that it's easier to analyze and replicate.
var myArray = [{
name: "A",
size: 20
}, {
name: "B",
size: 10
}, {
name: "C",
size: 30
}, {
name: "D",
size: 30
}];
myArray.sort(
function(a, b) {
if (a.size > b.size) {
return 1;
}
if (b.size > a.size) {
return -1;
}
return 0;
});
var names = [];
for (var i = 0; i <= myArray.length - 1; i++) {
names.push(myArray.name)
};
names;
The expected result is "B,A,C,D". B should go before A, since it's size is smaller than A's, while the order of C and D should remain unchanged, since their size is equal.
However, the result provided by ExtendScript is "B,A,D,C". For some reason, C and D become reversed.
I believe that the source of this behavior lies with ExtendScript's incorrect processing of the return 0 part.
In order to confirm that, I replaced the sorting funcion with
myArray.sort(
function(a, b) {
return 0;
});
which, according to my understanding of how compare functions are supposed to work, should return the whole array unchanged (no matter the input). But in this case ExtendScript processes it as "B,C,D,A".
I would be very grateful if anyone could confirm whether it is indeed a bug (or at least a lackluster implementation of the ECMAScript standard). Or is everything working as it should and the mistake is on my part?
Any hints as to the workaround for this issue would also be very helpful. Thanks!
