Skip to content

Instantly share code, notes, and snippets.

@codecademydev
Created July 4, 2021 22:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codecademydev/6706c579e3c23b0a52acaf62eaab2d08 to your computer and use it in GitHub Desktop.
Save codecademydev/6706c579e3c23b0a52acaf62eaab2d08 to your computer and use it in GitHub Desktop.
Codecademy export
// sortSpeciesByTeeth() Code Challenge
/* Code shows various function approaches for sorting by the
number of teeth, and also shows how to sort by the species
name
*/
// array of objects
const speciesArray = [ {speciesName:'shark', numTeeth:50}, {speciesName:'dog', numTeeth:42}, {speciesName:'alligator', numTeeth:80}, {speciesName:'human', numTeeth:32}];
// 1. function expression without brackets { }, keyword return
// not used
const sortSpeciesByTeeth = spArrObj => spArrObj.sort((a, b) => a.numTeeth - b.numTeeth);
// 2. function expression with brackets { }, use return keyword
const sortSpeciesByTeeth02 = spArrObj => spArrObj.sort((a, b) => {return a.numTeeth - b.numTeeth;
});
// 3. function declaration approach
function sortSpeciesByTeeth03(spArrObj) {
return spArrObj.sort((a, b) => a.numTeeth - b.numTeeth);
}; // end function
// **** Function and callback fn to sort by speciesName ***
// Callback function to compare strings
// see MDN Array.protoytpe.sort() Description for more details
// SpN = speciesName
function compareStr(aSpN, bSpN) {
let na = aSpN.toLowerCase(), // first convert name to lower case
nb = bSpN.toLowerCase();
// compare names and return -1, 1, or 0 for order
if (na < nb) {
return -1; // leave str a and b in same order
} else if (na > nb) {
return 1; // sort b before a
} else {
return 0; // leave str a and b in same order
}; // end if
}; // end function compareStr
// Function .sort by speciesName, callback to compareStr() fn
function sortSpeciesByName(spArrObj) {
return spArrObj.sort((a, b) => (compareStr(a.speciesName, b.speciesName)));
}; // end function
// **** Call functions ****
// Calls functions to sort by speciesTeeth
console.log(sortSpeciesByTeeth(speciesArray));
console.log(sortSpeciesByTeeth02(speciesArray));
console.log(sortSpeciesByTeeth03(speciesArray));
/* output for all three function calls:
// [ { speciesName: 'human', numTeeth: 32 },
// { speciesName: 'dog', numTeeth: 42 },
// { speciesName: 'shark', numTeeth: 50 },
// { speciesName: 'alligator', numTeeth: 80 } ]
*/
// Calls function to sort by speciesName
console.log(sortSpeciesByName(speciesArray));
/* output for sortSpeciesByName:
[ { speciesName: 'alligator', numTeeth: 80 },
{ speciesName: 'dog', numTeeth: 42 },
{ speciesName: 'human', numTeeth: 32 },
{ speciesName: 'shark', numTeeth: 50 } ]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment