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

Sort() with non-existent values

I know that undefined values should be sent to the end of the result, but what about non-existent keys? (Shouldn’t be the same?) It seems sort doesn’t work in those cases:

const names = [
  {
    name: "John",
    age: 27
  },{
    name: "Charles",
  },{
    name: "Ellen",
    age: 30
  },{
    name: "Mario",
  },
  {
    name: "Emanuelle",
    age: 18
  }
]

names.sort(function (a, b) {
  if (a.age > b.age) return 1;

  if (a.age < b.age) return -1;

  return 0;
})

console.log(names) // Sort not working, prints original order

Ideally I want to modify the "names" array and not create/reassign more variables.

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 :

Your default sort solution is set to keep the item in its current position –> return 0. You could provide another conditional that captures undefined and return -1

const
names = [{ name: "John", age: 27 }, { name: "Charles" }, { name: "Ellen", age: 30 }, { name: "Mario" }, { name: "Emanuelle", age: 18 }];

names.sort(function (a, b) {
  if(b.age === undefined) return -1;
  if (a.age > b.age) return 1;
  if (a.age < b.age) return -1;
  return 0;
})

console.log(names) // Sort not working, prints original order
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