FAQ: Code Challenges: Intermediate JavaScript - sortSpeciesByTeeth()

I don’t really understand the solution. I get the feeling I have forgotten something important

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

Can anyone recommend an article explaining how this works. I understand how array.sort() works but the array.sort(a bunch of stuff) has me confused. I know what it does in this example but I’d like an article explaining how

Did you see the post above yours. It explains what the sort function is.

Today we use the concise body function for its simplicity and succinctness. In the past it would look like,

Array.sort(function (a, b) {
  return a - b
})

Check the top of the post for the reason why we need the function, at all.

Thanks!
I understand a bit better now but I’m still having trouble internalizing it. I decided to go back and review, I might have been moving forward a bit too quickly

1 Like

Hi guys,

var numbers = [4, 2, 5, 1, 3]; numbers.sort(function(a, b) { return a - b; }); console.log(numbers); // [1, 2, 3, 4, 5]

What is the meaning by a and b ? I don’t understand why we need to pass an arrow function to sort function.

Thanks!

function (a, b) {
    return a - b;
}

This function is called by the sort method to determine whether the sort is ascending, or descending. To reverse the order, switch a and b around.

There is a fuller explanation a few posts above this one. Give that a read.

1 Like

Hi mtf,

Could you explain in more detail why a - b will give ascending order and b - a will give descending order?

It has to do with how JS’s Array.sort() determines which value is greater (in subtraction, if a - b is negative, then b is greater). The sort method on its own will always put numbers that start with 1 before numbers that start with 2. That results in an improper sort.

a = [1,2,3,11,12,13,21,22,23, 31, 32, 33]
console.log(a.sort())

[ 1, 11, 12, 13, 2, 21, 22, 23, 3, 31, 32, 33 ]

The sort callback function is able to rectify this behavior.

1 Like

Is it because .sort has to receive a comparison to know what to sort if it is being used with an arrow function?

The comparison function is needed in all cases, regardless the function syntax.

Array.sort(function(a,b) {
    return a - b;
})

The concise body arrow function simplifies this…

Array.sort((a, b) => a - b)

Both perform the same action.

1 Like

Thank you, I think I meant to say “with a function” instead of arrow. Thank you for the clear guidance.

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

// Write your code here:

// 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. :joy:

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:

Gist: Codecademy export · GitHub

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.

Gist: Codecademy export · GitHub

Output:

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

1 Like