#JS Sort Function for integers

39 messages · Page 1 of 1 (latest)

mild gazelle
#

How does Javascript sort for integers actually work ?
The negative numbers are sorted in descending while 0 and positives are in ascending, why is that so ?
Also, how can I fix that ?

copper igloo
#

Thats how maths work

#

They are all ascending

#

Ascending means smallest to biggest

#

Oh I apologize

mild gazelle
copper igloo
#

My mistake

#

So weird.

errant rain
mild gazelle
errant rain
#

Doesn't sort numerically by default

copper igloo
copper igloo
mild gazelle
#

its ASCII

mild gazelle
copper igloo
#

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

errant rain
mild gazelle
copper igloo
#

Basically

#

Lets assume a is 6

#

and b is 4

mild gazelle
copper igloo
#

a-b which is 6-4 will return a positive number which means a is bigger than b

copper igloo
#

Then

#

The sort function will run the callback function for each pair in the array

#

Which means

mild gazelle
copper igloo
#

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

copper igloo
mild gazelle
#

Thanks @copper igloo @errant rain for the help 😃

#

!solved

copper igloo
#

Welcome