Arr.sort((a,b) => a-b); explanation - JavaScript - The freeCodeCamp Forum
Thu Dec 02 2021 23:32:06 GMT+0000 (Coordinated Universal Time)
Saved by
@tolanisirius
When you sort an array with .sort(), it assumes that you are sorting strings. When sorting numbers, the default behavior will not sort them properly.
The function that you pass tells how to sort the elements. It takes two parameters (a and b) that represent any two elements from the array. How the elements will be sorted depends on the function’s return value:
1) if it returns a negative value, the value in a will be ordered before b.
2) if it returns 0, the ordering of a and b won’t change.
3) if it returns a positive value, the value in b will be ordered before a.
When you pass the function (a, b) => a - b, you’re telling the .sort() function to sort the numbers in ascending order.
content_copyCOPY
https://forum.freecodecamp.org/t/arr-sort-a-b-a-b-explanation/167677
Comments