I'm implementing a sorting function like this.
const handleSort = (sortBy) => {
const compareFunction = (a, b) => {
if (a.medicineName < b.medicineName) {
return -1;
}
if (a.medicineName > b.medicineName) {
return -1;
}
return 0;
};
setFilteredMedicineList((prevFilteredMedicineList) => {
const copyOfPrevFilteredMedicineList = [...prevFilteredMedicineList];
copyOfPrevFilteredMedicineList.sort(compareFunction);
return copyOfPrevFilteredMedicineList;
});
};
I have an array of objects like this. The objects are the ones being sorted.
const myArray = [
{
medicineName: "Abcdefgh",
medicineId: 1,
},
{
medicineName: "Another name",
medicineId: 2,
},
];
I have a button that calls the handleSort function on click. Now my current compare function has the "medicine name" hardcoded. I want the function to be dynamic in that it uses the sortBy parameter to do the comparison. I know I can write another function for each case but I'm trying to force myself to write "clean code" to avoid what a friend told me is "smelly code". How can I implement something like this
const compareFunction = (a, b) => {
if (a.sortBy< b.sortBy) {
return -1;
}
if (a.sortBy > b.sortBy) {
return -1;
}
return 0;
};
I want in a way if I pass "medicineId" as a parameter that is what will be used to do the sorting. Note I have tried the above code and it is not doing what you would expect. Please help.