# 如何在沒有手動索引的情況下對Javascript中的字母等級進行排序

## sorting (5)

``````const grades = ['B+', 'F', 'A-', 'A+', 'B', 'B-', 'C+', 'C', 'C-', 'D+', 'D', 'D-', 'A']

return a - b;
});

`['A+', 'A', 'A-', 'B+', 'B', 'B-', 'C+', 'C', 'C-', 'D+', 'D', 'D-', 'F']`

``````const grades = ['B+', 'A', 'A-', 'A+', 'B', 'B-', 'C+', 'C', 'C-', 'D+', 'D', 'D-', 'F']
const result = grades.sort(function (a, b) {
if (a[0] < b[0]) {
return -1;
}
if (b[0] > a[0]) {
return 1;
}
if(a[0] === b[0]) {
if(a[1] && a[1] === "+") {
return -1;
}
}
return 0;
});
return result;
};

``````const grades = ['B+', 'F', 'A-', 'A+', 'B', 'B-', 'C+', 'C', 'C-', 'D+', 'D', 'D-', 'A']

a.charCodeAt(0) === b.charCodeAt(0) // If the letters are the same
? (a.charCodeAt(1) || 44) - (b.charCodeAt(1) || 44) // Just compare the postfix
: a.charCodeAt(0) - b.charCodeAt(0) // Otherwise compare the letters
);

ACII的 `+` 值為43，ASCII的 `-` 值為45，因此在沒有後綴的情況下可以使用44（即 `,` ）。

``````const grades = ['B+', 'F', 'A-', 'A+', 'B', 'B-', 'C+', 'C', 'C-', 'D+', 'D', 'D-', 'A']

a.charCodeAt(0) === b.charCodeAt(0)
? `\${a},`.charCodeAt(1) - `\${b},`.charCodeAt(1)
: a.charCodeAt(0) - b.charCodeAt(0)
);

``````const grades = ['B+', 'A', 'A-', 'A+', 'B', 'B-', 'C+', 'C', 'C-', 'D+', 'D', 'D-', 'F']
const sorted = grades.sort((a, b) => {
if (a === b) return 0 // if equal nothing changes
const ap = a.split('') // separate into letter and sign
const bp = b.split('')
if (ap[0] === bp[0]) { // if first letter is the same, we have to check second
return (ap[1] === "+" || b[1] === "-") ? -1 : 1
}
return ap[0].localeCompare(b[0]) // sort by letter grade
})
console.log(sorted)``````

``````const grades = ['B+', 'A', 'A-', 'A+', 'B', 'B-', 'C+', 'C', 'C-', 'D+', 'D', 'D-', 'F']

const order = { '+': -1, '-': 1, undefined: 0 };
return a[0].localeCompare(b[0]) || order[a[1]] - order[b[1]];
});

``````const grades = ['B+', 'F', 'A-', 'A+', 'B', 'B-', 'C+', 'C', 'C-', 'D+', 'D', 'D-', 'A']

const getCounter = (letter) => {
// Making simple math to sort it out
let letterCounter = letter.charCodeAt(0) * 10;
if(letter[1] === "+"){
letterCounter -= 1;
}
else if(letter[1] === "-"){
letterCounter += 1;
}
return letterCounter;
}