Why do I need to add two parameters here?

In this snippet, inside of the sort method, why do I need to add two parameters? Why can’t I just access the numTeeth property? Would that not suffice to have sort() place the numbers in ascending order?

const speciesArray = [ {speciesName:'shark', numTeeth:50}, {speciesName:'dog', numTeeth:42}, {speciesName:'alligator', numTeeth:80}, {speciesName:'human', numTeeth:32}]; const sortSpeciesByTeeth = (arr) => { const result = arr.sort((teeth1, teeth2) => teeth1.numTeeth > teeth2.numTeeth); return result } console.log(sortSpeciesByTeeth(speciesArray))

Compare function of sort method requires two parameters. You can’t just use arr.sort() without any parameters because you have an array of objects. So you have to explicitly describe how to compare these objects with each other.

1 Like

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