FAQ: Code Challenges: Intermediate JavaScript - sortSpeciesByTeeth()

This community-built FAQ covers the “sortSpeciesByTeeth()” exercise from the lesson “Code Challenges: Intermediate JavaScript”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Web Development

FAQs on the exercise sortSpeciesByTeeth()

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

Hi guys
The solution to this exercise confuses me :thinking:

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

//my original solution

const sortSpeciesByTeeth = arr => {

arr.sort(( a, b ) => {a.numTeeth - b.numTeeth});

return arr;
}

// the results i got

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

I’ve been stuck on it for awhile till I tried putting my comparative function arguments under regular brackets just on chance and then it worked fine got the correct order

// arr.sort(( a, b ) => (a.numTeeth - b.numTeeth)); //

Now I don’t understand why didn’t my original syntax work given the format for the sort.method clearly lists using curly brackets on the arguments ?
Am I missing something here?

thanks!

w3 sort method definition =
https://www.w3schools.com/jsref/jsref_sort.asp

Your original syntax would work if you insert the word return immediately after the opening curly brace {. The arrow syntax for functions has some specific rules. If you want to implicitly return whatever expression comes after the fat arrow => you don’t use curly braces { }. You also didn’t need the parenthesis ( ).
Either:

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

Or:

arr.sort((a,b) => a.numTeeth - b.numTeeth);

would have worked. It also worked with the parenthesis just like (3+4) is the same as 3+4. You simply encased your expression in parenthesis that weren’t needed, but caused no harm.
Hope this helps!

4 Likes

So the error resulted from the incorrect usage of the arrow function rather then the sort method hmm interesting

So if i would the normal function syntax would’ave worked as well?

arr.sort(function compareObj = (a,b) {return a.numTeeth - b.numTeeth});

Thanks for the quick reply! :slight_smile:

1 Like

Almost. Need to delete the =.
arr.sort(function compareObj(a,b) {return a.numTeeth - b.numTeeth});

Your main function in your original solution could also be shortened like so:

const sortSpeciesByTeeth = arr => arr.sort(( a, b ) => a.numTeeth - b.numTeeth);

Once again taking advantage of the implicit return without the curly braces { } or the return statement.
Happy Coding!

2 Likes

Much more efficient thanks!

1 Like

Hey community,
In this case, I don’t understand why “speciesObj1.numTeeth > speciesObj2.numTeeth” will make this return an ascending array. I do checked the MDN but still couldn’t figure it out how it works. P.s. following the MDN documentation I changed “speciesObj1.numTeeth > speciesObj2.numTeeth” to “speciesObj1.numTeeth - speciesObj2.numTeeth” and that also works. But, same, I still couldn’t figure out how it works. Can anyone help? Thanks!:sweat_smile:

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

6 Likes

Hello Guys,

I was wondering, why this is not acceptable?

const sortSpeciesByTeeth = arr => arr.sort(specie => specie.numTeeth);

As it says in the documentation: The sort() method sorts the elements of an array in place and returns the sorted array. The default sort order is ascending,

Thks!

2 Likes

Hi all, a couple of questions.

(1) Could anyone please explain how “a” and “b” access the numTeeth property by writing “a.numTeeth”.

When we call .sort on the array with the parameters (a, b), how is javascript interpreting these parameters.

(2) How does the (a - b) syntax result in sorting? This follows from the first question - I don’t understand how “a” and “b” are being interpreted to iterate through the array?

2 Likes

1 - That is the syntax of the language you can do a[“numTeeth”] or a.numTeeth. It doesn’t know whether a or b have a numTeeth property until it tries to use access it.

Not sure what you mean by how is JavaScript interpreting these parameters. Javascript uses duck typing, that is to say JavaScript doesn’t care what a and b are so long as it can be used they way it is being asked to (i.e. so long as it has a numTeeth property in this case). Even then, as said above it doesn’t care about that until it tries to use them.

2 - Sort expects a function that will return a negative number if b is bigger than the a, 0 if they are the same and a positive number if a is bigger than b. In this case a is bigger than b if a’s numTeeth is greater than b’s numTeeth property.

1 Like

30 posts were split to a new topic: Why wouldn’t my longhand version work?

I manage to find a solution to this exercise, but one thing I still don’t understand about “sort” is why I cannot use it on a specific property. My initial code was this:

const sortSpeciesByTeeth = species => species.numTeeth.sort(num = (a, b) => a> b);

But I got the error:
TypeError: Cannot read property ‘sort’ of undefined

Why would species.numTeeth be undefined? I understood that in javascript you can chain properties and methods using dot notation, like “arr.property.method”, did I get it wrong?

Is numTeeth an array, or an object property? Does the object property have a sort() method?

What is the value passed to the species parameter? Does it have a numTeeth property? If I have an array of objects, the properties of those objects belong to the objects themselves not the array.

const myArray = [{num: 1}, {num: 2}, {num: 3}];
console.log(myArray.num);
myArray.forEach(obj => console.log(obj.num));

Output:

undefined
1
2
3

numTeeth is a property of an object of “species”. So if I understand correctly, i can do this chaining of property and method only using methods defined into the objects, and not built-in methods?

If you examine a couple of the earlier posts you will see how it is possible to sort an array of values, albeit those values are properties of objects. We just need to reference them correctly.

I understand from the MDN that setting up the compare function like so —
numbers.sort((a, b) => a - b);
— will use the subtraction to return either a positive or negative, and sort() will reorder accordingly. Can someone help me understand why it works the same way to use a > b within that function instead of a - b? What is being returned to sort here?

is a predicate that determines one of two (three) possible states (false, false, or true) in the relationship of a and b. a - b is an expression that results in three possible values, a negative, zero, or a positive. If positive then swap a and b. This gives us an ascending order sort.

So they are basically the same in that only one outcome will cause a swap, though using slightly different logic.

2 Likes

I have no idea how to complete this exercise. Can someone give me some advice on how to at least get started? Thanks.

Be sure to read up on the Array.sort() method so you get some understanding how it works.

Check the hint for an idea how to write a comparison function.

There are other clues within this topic. If you are still struggling, show us what code you have so far and we can go from there.