'what does - do in the sort function? why are we subtracting b from a? [duplicate]
Array.sort((a,b) => a - b);
so i have this typical sort for an Array of numbers. What does the subtract do? why are we subtracting b from a?
Solution 1:[1]
If the result is >0 :
b goes before a
If the result is <0 :
a goes before b
Solution 2:[2]
The sort function returns a number, because values greater than 0 are sorting b before a and values less than 0 are sorting a before b.
So if you are returning a-b you are sorting in ascending order (from small to big numbers)
You can read more about it here: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Moein moeinnia |
| Solution 2 |
