0

For sorting numbers in javascript we trick function sort() given in Javascript and it works perfectly. The trick is given below:

[12, 2, 23, 3, 43, 54].sort(function (a, b) { return a - b ; } ) Source #1 and Source#2

I didn't understand what exactly this a - b does. I have checked source code but its hard to understand. I checked following answer from stackoverflow but my doubt haven't cleared yet. Algorithm of JavaScript “sort()” Function

Can anyone explain me what exactly happens at a - b?

Rohit Sawai
  • 739
  • 1
  • 11
  • 28
  • 2
    maybe this helps: [`Array#sort`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) – Nina Scholz Sep 13 '19 at 09:00
  • 1
    the callback function you provide to the `sort` property takes as arguments a pair of 2 elements from the array and you define the way they are to be compared, in this case you subtract one from the other to decide which one is bigger – Krzysztof Krzeszewski Sep 13 '19 at 09:01
  • Possible duplicate of [Javascript Array.sort implementation?](https://stackoverflow.com/questions/234683/javascript-array-sort-implementation) – AZ_ Sep 13 '19 at 09:07
  • In this kind of programming you dont care about the actual algorithm that the .sort-method uses you only need to provide a rule thats says for every 2 elements in the list which one comes first. And thats what is defined in ```function (a, b) { return a - b ; }``` .... so it doesnt actually do anything its more a statement than an instruction – Mischa Sep 13 '19 at 09:14

2 Answers2

3

From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort:

If a and b are two elements being compared, then:

  1. If compareFunction(a, b) is less than 0, sort a to an index lower than b (i.e. a comes first).
  2. If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements.
  3. If compareFunction(a, b) is greater than 0, sort b to an index lower than a (i.e. b comes first).

When having a array of numbers, (a, b) => a - b (a simple subtraction) will thus behave as follow:

  • If a is greater than b, then a positive number will be returned (e.g. 5 - 3 = 2): according to the 3rd rule above, b comes first.
  • If a equals b, then 0 will be returned (e.g. 5 - 5 = 0): according to the 2nd rule above, leave a and b unchanged.
  • If a is smaller than b, then a negative number will be returned (e.g. 3 - 5 = -2): according to the 1st rule above, a comes first.
Community
  • 1
  • 1
sp00m
  • 47,968
  • 31
  • 142
  • 252
0

If you have an array like this

const points = [40, 100, 1, 5, 25, 10]

and you want to sort the array in ascending order, use this:

points.sort(function(a, b){return a - b});

for descending order:

points.sort(function(a, b){return b - a});
F. Müller
  • 3,969
  • 8
  • 38
  • 49