Closed Bug 1667587 Opened 4 years ago Closed 4 years ago

Incorrect Array.prototype.sort functionality

Categories

(Core :: JavaScript Engine, defect)

80 Branch
defect

Tracking

()

RESOLVED INVALID

People

(Reporter: ardeshireo, Unassigned)

Details

User Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:80.0) Gecko/20100101 Firefox/80.0

Steps to reproduce:

var result = [
"item11",
"item10",
"item9",
"item8",
"item7",
"item6",
"item5",
"item4",
"item3",
"item2",
"item1",
"this-should-be-top",
].sort((a) => (a === "this-should-be-top" ? -1 : 0));

console.log(result);

Actual results:

My array was returned as it was before.

Expected results:

'this-should-be-top' item should have moved to top of the list.

Component: Untriaged → JavaScript Engine
Product: Firefox → Core

Good(but destructive sorting):2006-10-05-04-trunk
Bad:2006-10-06-04-trunk

Before landing Bug 224128: 'this-should-be-top' will be 1st item. However, The original order for the rest of the items will not be preserved.
After landing of Bug 224128: It return as it was before.

Blocks: 224128
Status: UNCONFIRMED → NEW
Ever confirmed: true

I was discussing it with my colleagues in the past hour, and we concluded this is not necessarily a bug. This could be just different behavior between Firefox and Chrome (SpiderMonkey & V8). The problem is with my sort function, it is not a stable sort compare function, meaning all sort algorithms do not result in the same order using this compare function. Such as in Firefox, in which, the this-should-be-top is never the first argument of the sort function. (like a linear bubble sort)

Right now, I consider it not as a bug, but maybe a lack of specification. Not actually a lack, but maybe an improvement to specification is needed to make sure code using standard Java-Script method is functioning same across major browsers: e.g. latest versions of Firefox & Chromium.

So, sort((a, b) => (a === "this-should-be-top" ? -1 : b === "this-should-be-top" ? 1 : 0))
then results is as expected.

Status: NEW → UNCONFIRMED
Ever confirmed: false

it's not lack, but the spec clearly says it's implementation-defined.

https://tc39.es/ecma262/#sec-array.prototype.sort

22.1.3.27 Array.prototype.sort ( comparefn )
...
If comparefn is not undefined and is not a consistent comparison function for the elements of this array (see below), the sort order is implementation-defined.

I don't think specifying an algorithm for inconsistent comparison function makes much sense.
It will prevent any future performance improvement (like, adopting new sort algorithm, using different sort algorithm depending on array size, etc) for not-good reason.
and simply there's no correct behavior.

Status: UNCONFIRMED → RESOLVED
Closed: 4 years ago
Resolution: --- → WONTFIX
No longer blocks: 224128
Resolution: WONTFIX → INVALID
You need to log in before you can comment on or make changes to this bug.