-2

I know about sorting arrays, but I have the question I'm aching to find out.

For instance:

var array = [9,3,0,-2,15];

So, let's sort it:

function sortFunction(a, b){

  if(a < b) return -1; // or any number that less than zero, but why?
  if(a > b) return 1; // or any number that above zero, but why?
  if(a = b) return 0; // but why?

  // I know it may be easier a - b, I've written it for clarity

}

array.sort(sortFunction); //so we'll get correct result

How to understand why it has to return -1, 1, and 0 for sorting array?

P.S. Sorry if question seems stupid, I haven't found the answer in Google.

Jarvis
  • 384
  • 2
  • 6
  • 18

1 Answers1

2

From MDN:

  • If compareFunction(a, b) is less than 0, sort a to an index lower than b, i.e. a comes first.
  • If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements. Note: the ECMAscript standard does not guarantee this behaviour, and thus not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this.
  • If compareFunction(a, b) is greater than 0, sort b to a lower index than a.

There are three outcomes, so three possible return values.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335