Reputation: 27
I'm trying to sort array of strings ['d', 'CC', 'BB', 'b', 'a', 'Am','AMG']
in such order ["AMG", "Am", "a", "BB", "b", "CC", "d"]
Using
arr.sort(function (a, b) {
return a.toLowerCase().localeCompare(b.toLowerCase());
});
I get ["a", "Am", "AMG", "b", "BB", "CC", "d"]
Upvotes: 1
Views: 76
Reputation: 386600
You could chain some sort criteria, after swapping the case of the letters, then
function swap(s) {
return Array.from(s, c => c.toUpperCase() === c ? c.toLowerCase() : c.toUpperCase()).join('');
}
var array = ['d', 'CC', 'BB', 'b', 'bb', 'a', 'Am', 'AMG'];
array.sort((a, b) => {
var aa = swap(a),
bb = swap(b);
return a[0].toLowerCase().localeCompare(b[0].toLowerCase())
|| bb.length - aa.length
|| aa.localeCompare(bb);
});
console.log(array); // ["AMG", "Am", "a", "BB", "b", "CC", "d"]
Upvotes: 2