FAQ: Code Challenges: Intermediate JavaScript - sortSpeciesByTeeth()

Is that supposed to be a function, or a value?

What is the instruction in step 1?

What I believe is happening is JavaScript coverts the boolean result of the comparison to a number. true becomes 1 and false becomes 0. This can be proven with:

Number(true)   //=> 1
Number(false) //=> 0

Then it is applying the rules according to the MDN documentation
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

  • If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements.
  • If compareFunction(a, b) returns greater than 0, sort b to an index lower than a (i.e. b comes first).

Why did they choose to make the sort function so complicated?

return specArr.sort((a,b) => {
    return a.numTeeth > b.numTeeth;
  });

This leads to ascending order sorting. I read it as when a is larger than b push it into the array, though the result is the complete opposite. Is anyone able to fully wrap their head behind this function and what it is really doing and what the logic is behind it and how it came about?

Good night :wink:

I have a problem. I know the excercise i supposed to be solved by using the .sort () method. But i tried to build my own comparison and i dont know why it does not work. Can someone help me understand why?

Thanks in advance!

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

// Write your code here:

const sortedSpecies = [];
const sortSpeciesByTeeth = (array) => {

  for (i=0; i<array.length; i++) {
    if (array[i].numTeeth > array[i+1].numTeeth){
      sortedSpecies.unshift(array[i]);
    }
    else {
      sortedSpecies.push(array[i]);
    }
  };
return sortedSpecies;
};

console.log(sortSpeciesByTeeth(speciesArray));

Greetings,

Daniel

The simplest form of sort is Bubble Sort and that requires two loops, one nested within the other. Your code is attempting to sort in a single pass which is not always possible, hence the need for nested loops.

Thank you for your quick respond. I will try to read into this bubble sort thing, just to satisfy my curiosity :slight_smile:

1 Like

You’re welcome. There are few topics on the forums, including this one…

Bubble Sort

Study the way the algorithm works. Once you get a clear picture it should be fairly simple to apply it to your solution. Keep us posted.