Sort() on array with objects


#1

During the javascript practice, above snippet, I can’t easily understand how the sort() works on the array with objects.

I searched MDN that callback function in sort() is used for determining order rule.

as the ’ speciesObj1.numTeeth > speciesObj2.numTeeth’ seems returning nothing in value.


#2

Seems?

This is testable so don’t guess. Find out. Judging by their names they are numbers, so:

console.log(3 > 1)

I’m guessing that’s not the issue (if there is any at all)
But perhaps there are a couple of things that you need to happen in the code, you could use console.log to get information out of your program


#3

I know that this comparison results in Boolean type value, ‘true’.

Yet the compareFunction(a,b) needs return value in data type number.

Or does javascript accept Boolean data type in number as well? like C does.


#4

That is a bug in your comparison function, yes.

C doesn’t have booleans at all, as for javascript I dare not say to what extent booleans are interchangeable with 1 and 0. There’s a bigger problem with that though: booleans can only represent two values and your comparison function needs to be able to produce at least three different results.

If you’re asking why it seems to work despite an incorrect comparison function, then yes, your comparison function does the right thing in some cases and if only those are used then you’ll end up with a correctly sorted array. It does return a positive value when a is greater than b, and it does return 0 when a is equal to b. Changing the data in the array may give you cases where it comes out sorted incorrectly.