sortSpeciesByTeeth() lesson - different answers in different enviroments

Hello everyone!

This question was asked here before, but the person didn’t get any answers.
I am interested in figuring out what is going on as well.

Solution to the excercise sortSpeciesByTeeth() asks you to make a function which sorts keys of an object in ascending order. After solving it, I decided to look up the answer by Codecademy. And since I code in VScode instead of playground provided to us, I pasted the answer there. To my surprise, console.log output came out different:

Website:

VScode:

Codecademy’s playground:

Sorting algorithm solution provided by Codecademy works only in the task itself, while other editors show that .sort does not work.

Solution provided:

const speciesArray = [ {speciesName:'shark', numTeeth:50}, {speciesName:'dog', numTeeth:42}, {speciesName:'alligator', numTeeth:80}, {speciesName:'human', numTeeth:32}];

const sortSpeciesByTeeth = arr => arr.sort((speciesObj1, speciesObj2) => speciesObj1.numTeeth > speciesObj2.numTeeth)

/*
// As a function declaration AND using a named function:
function sortSpeciesByTeeth(arr) {
      const compareTeeth = (speciesObj1, speciesObj2) => speciesObj1.numTeeth > speciesObj2.numTeeth
      return arr.sort(compareTeeth)
}
*/

console.log(sortSpeciesByTeeth(speciesArray))

Is it a bug, or am I missing something?

1 Like

So first off, I’ll start by saying that the VS Code and Codecademy Playground environments are working correctly to my expectation. If we look at the docs for the .sort() method Array.prototype.sort we’ll see that the return from the internal function for sort must be an integer, as the sorting logic is carried out based on the relation of the function result to 0. Thus nothing should happen when the sorting algorithm received a bool as it’ll not to any type conversion to my knowledge, it’ll just fail the comparison and move on. This would explain why most places give you the input array back.

As for the lesson env giving a different result it’s unclear. My best guess is that Codecademy built something in to convert boolean to integer for some reason. Either that or it’s something to do with their JS interpreter specifically in the lesson setting. Either way, I would recommend going with Node.js output in VS Code as your standard “this is how JS works”. And that would require your comparison function returning an int instead of a boolean aka. changing the > to be -.

2 Likes
1 Like

Thank you for your message Adam, now I get it.
Mystery is solved. :disguised_face: