Sorting strings

Suppose we have the following array:

let names = ['Ana', 'ana', 'john', 'John']; 
console.log(names.sort()); 

What do you think would be the output? The answer is as follows:

["Ana", "John", "ana", "john"] 

Why does ana come after John when a comes first in the alphabet? The answer is because JavaScript compares each character according to its ASCII value. For example, A, J, a, and j have the decimal ASCII values of A: 65, J: 74, a: 97, and j: 106.

Therefore, J has a lower value than a, and because of this, it comes first in the alphabet.

For more information about the ASCII table, visit http://www.asciitable.com.

Now, if we pass compareFunction, which contains the code to ignore the case of the letter, we will have the output ["Ana", "ana", "john", "John"], as follows:

names = ['Ana', 'ana', 'john', 'John']; // reset array original state 
console.log(names.sort((a, b) => { 
  if (a.toLowerCase() < b.toLowerCase()) { 
    return -1; 
  } 
  if (a.toLowerCase() > b.toLowerCase()) { 
    return 1; 
  } 
  return 0; 
})); 

In this case, the sort function will not have any effect; it will obey the current order of lower and uppercase letters.

If we want lowercase letters to come first in the sorted array, then we need to use the localeCompare method:

names.sort((a, b) => a.localeCompare(b)); 

The output will be ["ana", "Ana", "john", "John"].

For accented characters, we can use the localeCompare method as well:

const names2 = ['Maève', 'Maeve']; 
console.log(names2.sort((a, b) => a.localeCompare(b))); 

The output will be ["Maeve", "Maève"].