0

I wanted to sort an array in a way that one type of element always was first. Other than that, the order was irrelevant. I wrote the following and went on with my day.

["a","b","a","b"].sort((x,y) => x === "b" ? 0 : 1);

Chrome gives me the expected result;

["b","b","a","a"]

But IE and Safari does not.

I understand how to get the result I want, and I guess the problem is in the way the Browser does the comparison between items, but I'm curious of a more in-depth explanation.

t.niese
  • 39,256
  • 9
  • 74
  • 101
Jesper Palm
  • 7,170
  • 31
  • 36
  • 2
    "I understand how to get the result I want" Are you sure? Your comparison function invokes an implementation-defined sort order. In fact, Chrome 71 does not produce that result. – Josh Lee Oct 05 '18 at 14:29
  • Check out this [link](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#Description). Returning '0' does not change anything. Return '-1' instead. – Erik T. Oct 05 '18 at 14:29
  • @JoshLee The question was more around why this worked in Chrome. I understand that this might be a misuse of sort but could you explain why that would be? (Tested in Chrome 69) – Jesper Palm Oct 05 '18 at 14:33
  • 1
    Your comparison function is [totally inconsistent](https://stackoverflow.com/a/24080786/1048572). It doesn't "work" in Chrome, you just were lucky. – Bergi Oct 05 '18 at 14:40
  • 1
    The comparison function is not valid according to the [22.1.3.24 Array.prototype.sort (comparefn)](https://www.ecma-international.org/ecma-262/6.0/#sec-array.prototype.sort), so the result is undefined and depends on the used sort algorithm. You even cannot be sure that it works just because it looks right, it could just be that it seems right for your test cases. – t.niese Oct 05 '18 at 14:47

1 Answers1

3

your question is answered in here:

in short, your compare function is not correct, it should return 1,-1, 0 as return values for example:

array.sort(function(a, b) {
    if (a.id < b.id) return -1;
    if (a.id > b.id) return 1;
    return 0;
})
ganjim
  • 1,234
  • 1
  • 16
  • 30