You could check in the sort callback if both Acr
-values are strings, if yes return the result of the string-comparison. If only one of the values is a string give it priority and if neither of them is a string (I'm assuming you only have numbers and strings as their values), return the (signed) difference of the values. Something like this should do it:
const arr=[
{"Id":949,"Acr":900,"Definition":"ADefBulk6","index":0},
{"Id":947,"Acr":502,"Definition":"ADefBulk6","index":0},
{"Id":762,"Acr":"AW","Definition":"Anti","ID":762,"index":1},
{"Id":72,"Acr":"AO","Definition":"Corporate","ID":762,"index":1},
{"Id":76,"Acr":"AA","Definition":"Corporate","ID":762,"index":1}];
arr.sort((a, b) => {
if (typeof a.Acr === 'string' && typeof b.Acr === 'string') {
return a.Acr.localeCompare(b.Acr);
} else if (typeof a.Acr === 'string') {
return -1;
} else if (typeof b.Acr === 'string') {
return 1;
} else {
return Math.sign(a.Acr - b.Acr);
}
});
console.log(arr);
For values with number-strings, you can do:
const arr = [
{"Id": 949, "Acr": "900", "Definition": "ADefBulk6", "index": 0},
{"Id": 947, "Acr": "502", "Definition": "ADefBulk6", "index": 0},
{"Id": 762, "Acr": "AW", "Definition": "Anti", "ID": 762, "index": 1},
{"Id": 72, "Acr": "AO", "Definition": "Corporate", "ID": 762, "index": 1},
{"Id":73, "Acr": "401(c)(d)","Definition":"Corporate","ID":762,"index":1},
{"Id": 76, "Acr": "AA", "Definition": "Corporate", "ID": 762, "index": 1}];
arr.sort((a, b) => {
const nrA = Number.parseInt(a.Acr);
const nrB = Number.parseInt(b.Acr);
if (isNaN(nrA) && isNaN(nrB)) {
return a.Acr.localeCompare(b.Acr);
} else if (isNaN(nrA)) {
return -1;
} else if (isNaN(nrB)) {
return 1;
} else {
return Math.sign(nrA - nrB);
}
});
console.log(arr);