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

How can I skip a string during sorting in js

I am trying to sort the merit list from my array of objects, but on my object, there is a string "Failed", I want to skip it during the sorting but when sorting is done the failed merit should be added at the end

const markSheet = [{ merit: 1 }, { merit: "Failed" }, { merit: 2 }];
const defineMerit = (markSheet) => {
  return markSheet
    .filter((item) => item.merit !== "Failed")
    .sort((a, b) => a.merit - b.merit);
};
console.log(defineMerit(markSheet))

example:

[
  {
    "merit": 1
  },
  {
    "merit": 2
  },
  {
    "merit": "Failed"
  }
]

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 :

Put the failed check inside the sort callback (compare the difference of whether an item is Failed or not)

const markSheet = [{ merit: 1 }, { merit: "Failed" }, { merit: 2 }];
const defineMerit = (markSheet) => {
  return markSheet
    .sort((a, b) => (
      ((a.merit === 'Failed') - (b.merit === 'Failed'))
      || a.merit - b.merit
    ));
};
console.log(defineMerit(markSheet))

or reverse the filter condition afterwards and combine with the sorted array

const markSheet = [{ merit: 1 }, { merit: "Failed" }, { merit: 2 }];
const defineMerit = (markSheet) => {
  const sorted = markSheet
    .filter((item) => item.merit !== "Failed")
    .sort((a, b) => a.merit - b.merit);
  return sorted.concat(
    markSheet.filter((item) => item.merit === "Failed")
  );
};
console.log(defineMerit(markSheet))
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