# FAQ: Code Challenges: Intermediate JavaScript - sortSpeciesByTeeth()

Hi everyone! I am trying to figure out why my solution fails. Here is my code…

const sortSpeciesByTeeth = x =>{
for (each in x){
x[each].numTeeth.sort();
}
}

We want to sort by number of teeth, which means sorting the whole array, not each object in the array. Scroll up to 9 Oct to see the solution given for comparison. Read down from there to see how the sort function is implemented.

1 Like

Hello Everyone!

Just for my own learning process, can you please tell me if I understood what the code below does, based on my comments explaining the functionality?

``````// This object array provides a different species of animals with their number of teeth as key-value pairs and the array will be used as an argument for the 'sortSpeciesByTeeth' function

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

// This function sorts the object array in ascending order based on the number of teeth each species possesses

const sortSpeciesByTeeth = speciesArr => {

// This statement uses the sort() method on the species array to sort the key-value pairs in ascending order by having declared 'animal1' and 'animal2' as 2 sub-arguments. These take 2 key-value pairs at a time to subtract the number and cause the ascension based on the subtraction's result.

return speciesArr.sort((animal1, animal2) => animal1.numTeeth - animal2.numTeeth)

}

// This function call takes the 'speciesArray' as an argument to be passed to the function above

console.log(sortSpeciesByTeeth(speciesArray))

// Should print:

// [ { speciesName: 'human', numTeeth: 32 },

//   { speciesName: 'dog', numTeeth: 42 },

//   { speciesName: 'shark', numTeeth: 50 },

//   { speciesName: 'alligator', numTeeth: 80 } ]
``````

Thank you very much! I struggle to understand the body of code from after the built-in method we are using in these exercises.

This is correct in that sort iterates over the entire array by comparing two elements at a time. Specifically, the Compare function returns the result of animal1.numTeeth - animal2.numTeeth.

The important part to consider is how sort decides the correct order of the two elements being compared. From the MDN documentation, it uses the following logic:
If Compare function return value > 0, this means animal2.numTeeth is less than animal1.numTeeth so sort animal2 before animal1
If Compare function return value < 0, this means animal1.numTeeth is less than animal2.numTeeth so sort animal1 before animal2
If Compare function return value === 0, this means animal1.numTeeth is equal to animal2.numTeeth so leave the current order unchanged.

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

console.log(speciesArray);

const sortSpeciesByTeeth = arr => arr.sort((speciesOne,speciesTwo) => speciesOne.numTeeth > speciesTwo.numTeeth);

Can someone explain to me why this sorts in ascending order instead of descending? The way I read it, the sort method would return the elements ordered in a fashion where speciesOne > speciesTwo, so that is descending?

When the greater than sign is used, the larger value goes to the right. When the less than sign is used, the larger value goes to the left.

1 Like

2 posts were split to a new topic: What does the second => mean?

Hi all. Using the sort method to solve this problem and I am still getting the original array recreated as an output. If I return 1 instead of return -1 (in my sort method), I get the array in ascending order so it seems that the code is working but just not the other way. Could be wrong. Gist and output below:

Output:

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

``````// Write your code here:
teethCount => {
return this.numteeth;
}

const sortSpeciesByTeeth = species => {
return species.sort(teethCount => {
return -1;
});
}
``````

Can you describe how you expect this code to run?

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.

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}];

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?

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.

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

1 Like

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

``````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.