Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort array order of lower and uppercase [duplicate]

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

like image 319
Hamza Neffati Avatar asked Dec 23 '22 22:12

Hamza Neffati


2 Answers

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.

like image 66
Ghoul Ahmed Avatar answered Jan 05 '23 08:01

Ghoul Ahmed


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;
}));
like image 35
Manish Khedekar Avatar answered Jan 05 '23 10:01

Manish Khedekar