#JS Sort Function for integers
39 messages · Page 1 of 1 (latest)
huh
Thats how maths work
They are all ascending
Ascending means smallest to biggest
Oh I apologize
-1 > -3
I got the explanation for it.
Doesn't sort numerically by default
Okay thanks
YUP THIS
its ASCII
but why ASCII sort was used when people usually consider sort as numeric and not ASCII
If u wanna do by numbers, do this
let arr = [1, 5, 3, 6, -5, -3];
arr.sort((a, b) => a - b);
console.log(arr);
//[ -5, -3, 1, 3, 5, 6 ]```
Pretty much to compare all you need to do is return a negative number or positive number, if number is negative that means is a is smaller than b and if number which u return is positive it means a is greater than b and then the sort fuction sorts according to that therefore instead of writing a bunch of if statements, a-b is a much shorter solution
No idea. I'm sure there was some historical reason, but you can't go around changing these sorts of things easily regardless of expectations because there's so much browser code built off that spec.
Can you explain the function : (a, b) => a - b ?
Yes
Basically
Lets assume a is 6
and b is 4
with respect to the array you took
a-b which is 6-4 will return a positive number which means a is bigger than b
Okay thats pretty long but if u take array [3,-12,4,5]
Then
The sort function will run the callback function for each pair in the array
Which means
each possible pair of 2 numbers and feed it to the arrow function to get a- b ?
It will run the callback function (a, b) => a - b first for a=3, b=-12 then we do return a-b in the function so thats 3-(-12) so thats 3+12 so thats 15 which is a positive number we dont care that its 15 we just care that its a positive number, since it returns a positive number it means a is bigger than b so b will be put first and then a and then the next pair it picks is 3,4
I think so, yes.
This will sort ascendingly if u wanna do dscendingly then u can do b-a
Welcome