1

Can someone explain how subtracting one integer b from a returns an ordered array? E.g. I feel stupid for not understanding why this simple line solves this ..

var arr = [7, 2, 3, 100, 5, 6];

var sorted = arr.sort(function(a, b){
    return a - b; // What makes this line sort the integers??
});

console.log(sorted); // [2, 3, 5, 6, 7, 100];
HelloWorld
  • 105
  • 1
  • 8
  • 4
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#Description 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) is greater than 0, sort b to an index lower than a (i.e. b comes first). – danronmoon Jun 21 '19 at 20:33
  • 1
    Read carefully the link provided by @danronmoon, the best possible answer you can find is already there. – lealceldeiro Jun 21 '19 at 20:37
  • Also for more details on sorting in general, I'd recommend browsing around here: https://visualgo.net/en/sorting It has some great visualizations for understanding sorting algorithms as well as other types of algorithms. – prufrofro Jun 21 '19 at 20:37
  • @danronmoon: Ah, that makes sense now. Great link & explanation. – HelloWorld Jun 21 '19 at 20:38

1 Answers1

0

The Arry.sort callback function is expected to return a number lower than zero, zero or a number larger than zero indicating that a is smaller than, equal or larger than b. And that is exactly what the given function does. The arguments a and b are elements of the array that have been picked by the sort algorithm for comparison.

Carsten Massmann
  • 26,510
  • 2
  • 22
  • 43