Jeff
Jeff

Reputation: 21

Array.sort() compare function

The code I found to sort a list of numbers by ascending order is:

arr.sort((a,b) => a-b);

I don't understand how the compare function works. What if you do arr.sort((a,b) => a+b)?

Upvotes: 0

Views: 947

Answers (1)

Mingwei Samuel
Mingwei Samuel

Reputation: 3272

The sort function uses the sign of the value returned by the comparator:

  • Positive means A > B.
  • Negative means A < B.
  • Zero means A == B.

So a - b is just a neat shorthand which fulfills those cases.

Upvotes: 2

Related Questions