I want to create a new array that is copy of mine array and at the same time sort it using the value stored in numTeeth. I’m using the function sort to accomplish this task. The problem is that if I try to debug it using a console log it show as result the undefined value.
const speciesArray = [
{speciesName:'shark', numTeeth:50},
{speciesName:'dog', numTeeth:42},
{speciesName:'alligator', numTeeth:80},
{speciesName:'human', numTeeth:32}
];
const sortSpeciesByTeeth = arrayIn => {
arrayIn.sort( function (a, b) {
return a.numTeeth - b.numTeeth;
});
}
console.log(sortSpeciesByTeeth(speciesArray))
While if I use the same code without declaring it as separate function it works despite it sort the original array. What I don’t want in the final code. Example
const speciesArray = [
{speciesName:'shark', numTeeth:50},
{speciesName:'dog', numTeeth:42},
{speciesName:'alligator', numTeeth:80},
{speciesName:'human', numTeeth:32}
];
speciesArray.sort( function (a, b) {
return a.numTeeth - b.numTeeth;
});
console.log(speciesArray)
>Solution :
1) You have to return something from the function sortSpeciesByTeeth, by default undefind is returned.
2) If you want a copy of original array then you can use spread syntax
The sort() method sorts the elements of an array in place and returns the sorted array. – MDN
const sortSpeciesByTeeth = (arrayIn) => {
return [...arrayIn.sort((a, b) => a.numTeeth - b.numTeeth)];
};
or
const sortSpeciesByTeeth = (arrayIn) => [
...arrayIn.sort(({ numTeeth: nT1 }, { numTeeth: nT2 }) => nT1 - nT2),
];
const speciesArray = [
{ speciesName: "shark", numTeeth: 50 },
{ speciesName: "dog", numTeeth: 42 },
{ speciesName: "alligator", numTeeth: 80 },
{ speciesName: "human", numTeeth: 32 },
];
const sortSpeciesByTeeth = (arrayIn) => {
return [
...arrayIn.sort(function (a, b) {
return a.numTeeth - b.numTeeth;
}),
];
};
console.log(sortSpeciesByTeeth(speciesArray));
/* This is not a part of answer. It is just to give the output full height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }