Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sorting an Array using .sort in an function equals Undefined in JavaScript

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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; }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading