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?

4
  • 2
    maybe this helps: Array#sort Commented Sep 13, 2019 at 9: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 Commented Sep 13, 2019 at 9:01
  • Possible duplicate of Javascript Array.sort implementation? Commented Sep 13, 2019 at 9: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 Commented Sep 13, 2019 at 9:14

2 Answers 2

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.
Sign up to request clarification or add additional context in comments.

Comments

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});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.