If I have an array like this:
var tab = ['1185 Design','3 D Exhibits','44Doors', '4Concepts','ABC Data','acceleration'];
And I want to sort it so that small letter 'a'
element comes before capital letter 'A'
element.
Use Array#sort()
method with String#localeCompare()
var tab = ['1185 Design', '3 D Exhibits', 'nb', 'N', 'cd', '44Doors', '4Concepts', 'ABC Data', 'acceleration'];
tab.sort(function(a, b) {
return sortFn(a, b);
});
function sortFn(a, b) {
// if both are equal return 0
if (a == b) return 0;
// if first characters are equal call the same function with remaining (recursion)
if (a.charAt(0) == b.charAt(0)) return sortFn(a.slice(1), b.slice(1))
// check lowercase or uppercase based on that return value
if (/^[a-z]/.test(a.charAt(0)) && /^[A-Z]/.test(b.charAt(0))) return -1;
if (/^[a-z]/.test(b.charAt(0)) && /^[A-Z]/.test(a.charAt(0))) return 1;
// otherwise ude normal compare function
return a.localeCompare(b);
}
console.log(tab);
UPDATE : In case if you want to sort with alphabetical order and small letter should have higher precedence only if they are equal then do something like.
var tab = ['1185 Design', '3 D Exhibits', 'nb', 'N', 'cd', '44Doors', '4Concepts', 'ABC Data', 'acceleration'];
tab.sort(function(a, b) {
return sortFn(a, b);
});
function sortFn(a, b) {
// if both are equal return 0
if (a == b) return 0;
// if first characters are equal call the same function with remaining (recursion)
if (a.charAt(0) == b.charAt(0)) return sortFn(a.slice(1), b.slice(1))
// check lowercase or uppercasebased on that return value in case the letters are equal
if (a.charAt(0).toLowerCase() == b.charAt(0).toLowerCase()) {
if (/^[a-z]/.test(a.charAt(0)) && /^[A-Z]/.test(b.charAt(0))) return -1;
if (/^[a-z]/.test(b.charAt(0)) && /^[A-Z]/.test(a.charAt(0))) return 1;
}
// otherwise ude normal compare function
return a.localeCompare(b);
}
console.log(tab);