I am attempting to create a custom sorting method with the following order:
- special character ( - first, _ last)
- digit
- alphabets
For instance, when sorting the array below
var words = ['MBC-PEP-1', 'MBC-PEP01', 'MBC-PEP91', 'MBC-PEPA1', 'MBC-PEPZ1', 'MBC-PEP_1'];
the desired result should be
MBC-PEP-1,MBC-PEP_1,MBC-PEP01,MBC-PEP91,MBC-PEPA1,MBC-PEPZ1
However, with my current code, the result is
"MBC-PEP-1", "MBC-PEP01", "MBC-PEP91", "MBC-PEP_1", "MBC-PEPA1", "MBC-PEPZ1"
I am unsure of how to achieve the desired sorting order.
function MySort(alphabet)
{
return function(a, b) {
var lowerA = a.toLowerCase()
var lowerB = b.toLowerCase()
var index_a = alphabet.indexOf(lowerA[0]),
index_b = alphabet.indexOf(lowerB[0]);
if (index_a === index_b) {
// same first character, sort regularly
if (a < b) {
return -1;
} else if (a > b) {
return 1;
}
return 0;
} else {
return index_a - index_b;
}
}
}
var items = ['MBC-PEP-1', 'MBC-PEP01', 'MBC-PEP91', 'MBC-PEPA1', 'MBC-PEPZ1', 'MBC-PEP_1'],
sorter = MySort('-_0123456789abcdefghijklmnopqrstuvwxyz');
console.log(items.sort(sorter));