Suppose we have a following array
let names = ['Malek', 'malek', 'sana', 'ghassen', 'Ghada', 'Samir'];
console.log(names.sort());
the result is a follows:
["Ghada", "Malek", "Samir", "ghassen", "malek", "sana"]
JavaScript compares each character according to its ASCII value.
I want to sort by lowercase letters to come first in the sorted array,
the expected output:
["Ghada", "ghassen", "malek", "Malek", "Samir", "sana"]
thanks
Try this with localeCompare:
const names = ["Ghada", "Malek", "Samir", "ghassen", "malek", "sana"];
const result = names.sort((a, b) => a.localeCompare(b));
console.log(result);
The localeCompare() method returns a number indicating whether the string comes before, after or is equal as the compareString in sort order.
Try out as,
let names = ['Malek', 'malek', 'sana', 'ghassen', 'Ghada', 'Samir'];
console.log(names.sort(function(a, b) {
var nameA = a.toUpperCase(); // ignore upper and lowercase
var nameB = b.toUpperCase(); // ignore upper and lowercase
if (nameA < nameB) {
return -1;
}
if (nameA > nameB) {
return 1;
}
// names must be equal
return 0;
}));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With