1

I have got a very strange result trying to sort an array:

[0,1,2,3,4,5,6,7,8,9,10].sort(function(a,b) {return a > b;})

Result:

[5, 0, 1, 2, 3, 4, 6, 7, 8, 9, 10]

I would like to understand, why is this result return? I know, that sort function should be written like this:

[0,1,2,3,4,5,6,7,8,9,10].sort(function(a,b) {return a - b;})
11
  • 1
    works fine for me Commented Mar 20, 2017 at 12:55
  • 1
    The result is probably implementation dependant. Commented Mar 20, 2017 at 12:56
  • 4
    developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Does not expect a Boolean Commented Mar 20, 2017 at 12:57
  • 2
    I'm not sure why it messes up, but you can expand the a>b to return only 0 or 1, no -1, and get the same results. [0,1,2,3,4,5,6,7,8,9,10].sort(function(a,b) {return (a-b) > 0 ? 1 : 0;}) Commented Mar 20, 2017 at 12:57
  • 2
    your first sort function is not kind of symetrical in the way as it should be: sortFn(a, b) === -sortFn(b, a), because you get only values of 0 and 1 (the numerical value). Commented Mar 20, 2017 at 13:03

1 Answer 1

1

Yes you could get strange sorting results, for example in Chrome, where the sorting starts with the first and last element and goes on with the middle element.

Basicall you get the following protocoll

                  return  needed
  a    b   a > b   value   value  comment
---  ---  ------  ------  ------  -----------
  0   10   false       0      -1  wrong value
  0    5   false       0      -1  wrong value
  2    0    true       1       1
  9    0    true       1       1
  8    0    true       1       1
  7    0    true       1       1
  6    0    true       1       1
  1    0    true       1       1
  4    0    true       1       1
  3    0    true       1       1
  2    3   false       0      -1  wrong value
  3    4   false       0      -1  wrong value
  4    1    true       1       1
  3    1    true       1       1
  2    1    true       1       1
  4    6   false       0      -1  wrong value
  6    7   false       0      -1  wrong value
  7    8   false       0      -1  wrong value
  8    9   false       0      -1  wrong value
  9   10   false       0      -1  wrong value

Basically you get a value for equal items, bu you have unequal items to compare.

You need a stable sort function which is kind of symetrical in the way as it yields the nevgative value with switched parameters.

sortFn(a, b) === -sortFn(b, a)

If you return only values of 0 and 1, you miss -1.

console.log([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10].sort(function(a, b) {
    console.log(a, b, a > b);
    return a > b;
}));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.