["ax", "mof", "4", "63", "42", "3", "10", "[", "23", "adidas", "ba", ")", "ABC", "abc"] .sort((a, b) => { const aStr = String(a).toLowerCase(); const bStr = String(b).toLowerCase(); // Alphanumeric elements always come before non-alphanumeric elements const aIsAlphanumeric = isAlphanumeric(aStr); const bIsAlphanumeric = isAlphanumeric(bStr); if (aIsAlphanumeric && !bIsAlphanumeric) { return -1; } else if (bIsAlphanumeric && !aIsAlphanumeric) { return 1; } // Numerical elements always come before alphabetic elements const aNum = Number(a); const bNum = Number(b); // If both are numerical, sort in the usual fashion (smaller goes first) if (aNum && bNum) { return aNum - bNum; // If a is numerical but b isn't, put a first. } else if (aNum) { return -1; // If b is numerical but a isn't, put b first. } else if (bNum) { return 1; } // In all other cases, default to usual sort order. return aStr.localeCompare(bStr); }); let array = ["ax", "mof", "4", "63", "42", "3", "10", "[", "23", "adidas", "ba", ")", "ABC", "abc"]; array.sort((a, b) => { const aStr = String(a).toLowerCase(); const bStr = String(b).toLowerCase(); // Alphanumeric elements always come before non-alphanumeric elements const aIsAlphanumeric = isAlphanumeric(aStr); const bIsAlphanumeric = isAlphanumeric(bStr); if (aIsAlphanumeric && !bIsAlphanumeric) { return -1; } else if (bIsAlphanumeric && !aIsAlphanumeric) { return 1; } // Numerical elements always come before alphabetic elements const aNum = Number(a); const bNum = Number(b); // If both are numerical, sort in the usual fashion (smaller goes first) if (aNum && bNum) { return aNum - bNum; // If a is numerical but b isn't, put a first. } else if (aNum) { return -1; // If b is numerical but a isn't, put b first. } else if (bNum) { return 1; } // In all other cases, default to usual sort order. return aStr.localeCompare(bStr); }); console.log(array); function isAlphanumeric(str) { var code, i, len; for (i = 0, len = str.length; i < len; i++) { code = str.charCodeAt(i); if (!(code > 47 && code < 58) && // numeric (0-9) !(code > 64 && code < 91) && // upper alpha (A-Z) !(code > 96 && code < 123)) { // lower alpha (a-z) return false; } } return true; } Note: The isAlphanumeric function is taken from this answer and is defined as below:.
function isAlphanumeric(str) { var code, i, len; for (i = 0, len = str.length; i < len; i++) { code = str.charCodeAt(i); if (!(code > 47 && code < 58) && // numeric (0-9) !(code > 64 && code < 91) && // upper alpha (A-Z) !(code > 96 && code < 123)) { // lower alpha (a-z) return false; } } return true; };