FAQ: Code Challenges: Intermediate JavaScript - sortSpeciesByTeeth()

I realized that didn’t make sense after your reply so I re-did the code. Gist below. The 2 speciesObj are to replace the “a” and “b” used in the sort method examples (from the hint). Based on my understanding, a - b will give you ascending order but I was getting the original array back. I recalled that you said in a previous reply for a different problem that there has to be a return or console.log after curly braces and I added that for the correct result to output. @mtf you are really helping me understand all this and I can’t thank you enough.

Gist: Codecademy export · GitHub

Output:

[ { speciesName: ‘human’, numTeeth: 32 },
{ speciesName: ‘dog’, numTeeth: 42 },
{ speciesName: ‘shark’, numTeeth: 50 },
{ speciesName: ‘alligator’, numTeeth: 80 } ]

1 Like

Could anyone tell me why my code below is not working?

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

// Write your code here:
const sortSpeciesByTeeth = arr => {
  arr.sort(function(a,b){
  return a.numTeeth > b.numTeeth 
})
} //---------------------WHY NOT WORKING?!

// Feel free to comment out the code below when you're ready to test your function!
console.log(sortSpeciesByTeeth(speciesArray))

// Should print:
// [ { speciesName: 'human', numTeeth: 32 },
//   { speciesName: 'dog', numTeeth: 42 },
//   { speciesName: 'shark', numTeeth: 50 },
//   { speciesName: 'alligator', numTeeth: 80 } ]

The sort() method does sort the elements of an array in place (Documentation: Array.prototype.sort()).
In your code, sortSpeciesByTeeth doesn’t return anything, but the array passed as the argument is indeed mutated and sorted.

// Your code:
...
console.log(sortSpeciesByTeeth(speciesArray))
// Output: undefined
console.log(speciesArray)
// Output: speciesArray sorted by ascending numTeeth
// so array has indeed been sorted in place (mutated).

The reason you are getting undefined for the first console statement is because you have used curly braces for the body of the arrow function. So, you should return explicitly. Alternatively, you can remove the curly braces and let the array be returned implicitly. You can’t mix the two approaches. If you use curly braces, you can’t return implicitly. If you omit curly braces, you can’t return explicitly. Both forms below will work:

// Curly Braces and Explicit Return
const sortSpeciesByTeeth = arr => {
  return arr.sort(function(a,b){
  return a.numTeeth > b.numTeeth 
})
} 

// No curly braces and Implicit Return
const sortSpeciesByTeeth = arr => 
  arr.sort(function(a,b){
  return a.numTeeth > b.numTeeth 
})

Is it just me or is anyone else finding the CODE CHALLENGES: INTERMEDIATE JAVASCRIPT really hard? :sob: