CODE CHALLENGES: INTERMEDIATE JAVASCRIPT sortSpeciesByTeeth()


i had create a code of the SpeciesByTeeth() project like this :

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

// Write your code here:

const sortSpeciesByTeeth = (array) => {

 

  return array.sort(parseInt(species.numTeeth, 10))  

}

for sorts the array in ascending and sorts the array in ascending order based on the average number of teeth that species possesses ( numTeeth ) but not work correctly can soeone help me

if I look at the docs for the .sort() method (link), I see:

Syntax

arr.sort([compareFunction])

Parameters

compareFunction Optional
Specifies a function that defines the sort order. If omitted, the array elements are converted to strings, then sorted according to each character’s Unicode code point value.

If I then look at the argument you provide:

return array.sort(parseInt(species.numTeeth, 10)) 

parseInt(species.numTeeth, 10) does not look like a function?

sir please can you explain me how the number can be order in string format

Did the explanation on MDN not help?

there are couple of examples with explanation how such a function would need to work.

Thanks for your help, i will analyse it and resolve it

If you then need further help, let me know :slight_smile: but seems like a good idea to do further reading on how .sort() with compare function works

but if we make an array of species like this :
onst speciesArray = [ {speciesName:‘shark’, numTeeth:50}, {speciesName:‘dog’, numTeeth:42}, {speciesName:‘alligator’, numTeeth:80},{speciesName:‘human’, numTeeth:32},{speciesName:‘human’, numTeeth:9}] added an {speciesName:‘human’, numTeeth:9} in the array ,all the order wiil completly change so 9 will be in the last of order

which means you have two options: re-sort the array after adding elements

or inserting element in the array at the right place.

(post withdrawn by author, will be automatically deleted in 1 hour unless flagged)

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.