I am trying to sort the Strings with number and special characters combination.
But it is giving the wrong order.
<!DOCTYPE html>
<html>
<body>
<p>Click the button to sort the array.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function MySort(alphabet)
{
return function(a, b) {
var index_a = alphabet.indexOf(a[0]),
index_b = alphabet.indexOf(b[0]);
if (index_a === index_b) {
// same first character, sort regular
if (a < b) {
return -1;
} else if (a > b) {
return 1;
}
return 0;
} else {
return index_a - index_b;
}
}
}
function myFunction() {
var items = ["AB_UI08","AB_UI03","AB_UI07","AB_UI04","AB_UI05","AB_UI014","AB_UI01","AB_UI09","AB_UI010","AB_UI011","AB_UI012","AB_UI013","AB_UI06","AB_UI016","AB_UI07","AB_UI018","AB_UI019","AB_UI015","AB_UI020","AB_UI02"
],
sorter = MySort('*!@_.()#^&%-=+01234567989abcdefghijklmnopqrstuvwxyz');
console.log(items.sort(sorter));
}
</script>
</body>
</html>
It is giving the below response. ["AB_UI01", "AB_UI010", "AB_UI011", "AB_UI012", "AB_UI013", "AB_UI014", "AB_UI015", "AB_UI016", "AB_UI017", "AB_UI018", "AB_UI019", "AB_UI02", "AB_UI020", "AB_UI03", "AB_UI04", "AB_UI05", "AB_UI06", "AB_UI07", "AB_UI08", "AB_UI09"]
Unsorted array: ["AB_UI08","AB_UI03","AB_UI07","AB_UI04","AB_UI05","AB_UI014","AB_UI01","AB_UI09","AB_UI010","AB_UI011","AB_UI012","AB_UI013","AB_UI06","AB_UI016","AB_UI017","AB_UI018","AB_UI019","AB_UI015","AB_UI020","AB_UI02"]
Expected output: ["AB_UI01", "AB_UI02","AB_UI03", "AB_UI04", "AB_UI05", "AB_UI06", "AB_UI07", "AB_UI08", "AB_UI09", "AB_UI010", "AB_UI011", "AB_UI012", "AB_UI013", "AB_UI014", "AB_UI015", "AB_UI016", "AB_UI17", "AB_UI018", "AB_UI019", "AB_UI020"]
Appreciating your suggestions.