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:

Guys, I full on don’t understand none of this excercise. First of all in the solution for this, why do we get only two defined objects in the code block, when there are actually 4 species (objects) being compared here?

We can only compare two items at a time?

Fair enough, thank you for your answer. Although I still don’t fully understand how does this explain to the computer to put everything in order, or what values to assign to the two mentioned parameters…

1 Like

The heavy lifting is done by the .sort() method which uses an optimized algorithm (search ‘merge sort’, among other algos) that relies on the callback function to return the difference between a and b, which values are supplied by the method, iteratively. The algorithm is what selects a and b on each iteration. I could be wrong, but that only means the flipside is correct. Will need to examine this to overcome my memory deficiency: When the callback returns a negative value, the values referred by a and b are swapped, in-place.

To read up on a bubble sort algorithm, visit this thread:

Bubble Sort - #8 by mtf

That is not anywhere close to the algorithm that JS uses, but illustrates iteration, comparison and swapping (rather old school).

const bubbleSort = function (obj) {
  const f = function (n) {
    let a = [];
    let i = 0;
    while (a.length < n) {
      a.push(n - i++);
    }
    return a;
  }
  let r = f(obj.length)
  for (let i = 0; i < obj.length; i++) {
    r.pop();
    for (let j of r) {
      [a, b] = [obj[i], obj[j]]
      if (a > b) {
        [obj[i], obj[j]] = [obj[j], obj[i]]
      }
    }
  }
  return obj;
}
 > bubbleSort('threeblindmice'.split(''))
<- (14) ['b', 'c', 'd', 'e', 'e', 'e', 'h', 'i', 'l', 'i', 'm', 'n', 'r', 't']
 > bubbleSort([20, 26, 46, 14, 57, 11, 75, 31, 4, 51, 88, 1, 77, 20, 46, 25, 18, 98, 35, 45])
<- (20) [1, 4, 11, 14, 20, 18, 20, 26, 25, 31, 45, 35, 46, 46, 51, 57, 75, 88, 77, 98]

Thanks for your help. I’ll look into the materials you provided :smile:

1 Like

Can somebody explain to me how this works? How does this get sorted?

link here:
https://www.codecademy.com/journeys/front-end-engineer/paths/fecj-22-building-interactive-websites/tracks/fecj-22-javascript-syntax-part-ii/modules/wdcp-22-practice-javascript-syntax-arrays-loops-objects-iterators-3f82e7b8-a851-45e7-b4ca-57901365edcc/lessons/intermediate-javascript-coding-challenge/exercises/sort-species-by-teeth

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

Not sure that it will work. If you switch the > to < it will, in ascending order. Same thing if you swap out < and replace it with, -.

If you are asking how the method actually works, well, that will be for you to read up on. We’re not teachers, here, only learners.