Home > front end >  How can I skip a string during sorting in js
How can I skip a string during sorting in js

Time:07-03

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"
  }
]

CodePudding user response:

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))

  • Related