2

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

Hamza Neffati
  • 155
  • 1
  • 11

3 Answers3

6

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.

Ghoul Ahmed
  • 4,446
  • 1
  • 14
  • 23
1

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;
}));
Manish Khedekar
  • 392
  • 3
  • 13
0

You could use Intl.Collator():

let names = ['Malek', 'malek', 'sana', 'ghassen', 'Ghada', 'Samir', "A", 'a', 'ba', 'Ba', 'Cd', 'ca']; 
let res = names.sort(Intl.Collator('en').compare);

console.log(res);
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64