# I want to understand the sort array method

the sort array method is the hardest one I have ever faced I watched a lot of tutorials and did read about it the condition in the callback functions seems really hard to understand I do not want to copy solutions I want to understand it

here where I am stuck JavaScript’s default sorting method is by string Unicode point value, which may return unexpected results.

what unexpected values mean I used the sort method on an array of numbers before and it worked how could that be an unexpected result?

Try sorting the following array without providing a callback function:

[11, 1, 3, 2, 4, 5, 7, 6, 8, 9, 10]

2 Likes

@bbsmooth
ok but what does this means

If compareFunction(a,b) returns a value less than 0 for two elements a and b , then a will come before b

how could it even returns a value less than 0 if the callback function comparing a and b ?

Look at what the callback function is doing:

arr.sort(function(a, b) {
return a - b;
});

The return statement explicitly:

return a - b

If a and b are numbers then the callback is going to return a number as well and that number can be less than 0, equal to 0, or greater than 0.

I’m not sure if I completely understand your question though, so feel free to clarify.

ok this is a clear example where it is a minus operation
but how could it return less than 0 when the compare function comparing the a and b using the comparison operators it should return true or false

Are you referring to this:

arr.sort(function(a, b) {
return a === b ? 0 : a < b ? 1 : -1;
});

The syntax might be a little confusing but if you work it out you’ll see that it is returning a number, specifically either 1, 0, or -1.

And if you are thinking of something else, please provide a code example.

1 Like

The callback function, for each pair of values it’s given, should return less than zero for the one that should come before the other, zero if they’re the same, or greater than zero for one that should come after the other. Not true or false.

So

return a - b

Can also be written as

if (a < b) {
return -1;
} else if (a === b) {
return 0;
} else if (a > b) {
return 1;
}

It will do the same thing (note: for the array of numbers used in your example)

If the callback function returns the difference of two numbers of the array to be negative, then it knows that the first one is smaller than the second, which means they are already in a sorted order and nothing needs to be done. A 0 difference means both are same. And if the difference is positive then the two numbers definitely need to be sorted because the first is greater than the second.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.