I have an array of school grades that looks like the following.
(Note 'N' stands for no grades and 'K' stands for kindergarten)
const toSort = ['1','3','4','5','6','7','9','10','11','12','K','2','N','8'];
Using the JavaScript sort() method, I would like to arrange the array so it will look like:
const sorted = ['K','1','2','3','4','5','6','7','8','9','10','11','12','N'];
Here is my attempt at it:
const toSort = ['1', '3', '4', '5', '6', '7', '9', '10', '11', '12', 'K', '2', 'N', '8'];
toSort.sort();
// Produces: ["1", "10", "11", "12", "2", "3", "4", "5", "6", "7", "8", "9", "K", "N"]
const test = toSort.sort((a, b) => {
if (a === 'K') {
return -1;
}
return Number(a) < Number(b) ? -1 : Number(a) > Number(b) ? 1 : 0;
});
console.log(test)
https://jsbin.com/pocajayala/1/edit?html,js,console,output
How I can resolve this?
K< 1 whileN> 12?'K', make a special case for'N'. Then convert everything else to aNumber. No need for any ternary operators.Number("K")andNumber("N")are bothNaN. You only remove the case where the parameterais"K", not wherebis"K"or where either is"N".