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?
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:
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); }
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".
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.
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;
});
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);
});
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