Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript's sort method handling of capital letters

Tags:

javascript

Noticed something potentially odd with JavaScript's sort() method. Given the following array:

var arr = ['Aaa',
'CUSTREF',
'Copy a template',
'Copy of Statementsmm',
'Copy1 of Default Email Template',
'Copy11',
'Cust',
'Statements',
'zzzz'];

Calling sort on this array:

console.log(arr.sort());

Yields:

["Aaa", "CUSTREF", "Copy a template", "Copy of Statementsmm", "Copy1 of Default Email Template", "Copy11", "Cust", "Statements", "zzzz"] 

Is this correct? ie. CUSTREF is listed first, is this because of it's capital letters?

like image 408
benhowdle89 Avatar asked Feb 11 '14 11:02

benhowdle89


People also ask

How to sort a string in alphabetical order using JavaScript?

If an element with ASCII code greater than the other element is found, you need to swap the elements. Follow the same approach for all the elements and when iterated over the whole array you’ll have a string with letters sorted in alphabetical order. Here is how the JavaScript function to sort string letters looks like:

How to sort capital letters before lower case in JavaScript?

However you have to add an extra step to sort capital letters before lower case once: function cmp (x,y) { if (x.toLowerCase () !== y.toLowerCase ()) { x = x.toLowerCase (); y = y.toLowerCase (); } return x > y ? 1 : (x < y ? -1 : 0); // or return x.localeCompare (y); }

What is the default order of sorting in JavaScript?

By default, the sort order is ascending, built upon converting the elements into strings and then comparing their sequences of UTF-16 code unit values. Number sorting can be incorrect as the sort ( ) method sorts numbers in the following order: "35" is bigger than "225", because "3" is bigger than "2".

What is the difference between sort() and sort()?

The sort () sorts the elements of an array. The sort () overwrites the original array. The sort () sorts the elements as strings in alphabetical and ascending order. Sorting alphabetically works well for strings ("Apple" comes before "Banana"). But, sorting numbers can produce incorrect results.


2 Answers

That is correct. The strings are being sorted in a binary fashion, using the ordinal values of the characters themselves.

For a case-insensitive sort, try this:

arr.sort(function(a,b) {
    a = a.toLowerCase();
    b = b.toLowerCase();
    if( a == b) return 0;
    return a < b ? -1 : 1;
});
like image 154
Niet the Dark Absol Avatar answered Sep 24 '22 11:09

Niet the Dark Absol


You are correct, it is because of capital letters. If you are sorting strings which might have non ASCII characters such as ä and ö you should use String.localeCompare(). This also fixes the capital letter problem.

arr.sort(function (a, b) {
    return a.localeCompare(b);
});
like image 23
Mika Tuupola Avatar answered Sep 24 '22 11:09

Mika Tuupola