Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
6
rated 0 times [  9] [ 3]  / answers: 1 / hits: 15109  / 10 Years ago, tue, february 11, 2014, 12:00:00

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?


More From » javascript

 Answers
83

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;
});

[#72591] Monday, February 10, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
turnerf

Total Points: 620
Total Questions: 101
Total Answers: 109

Location: French Polynesia
Member since Tue, Jul 7, 2020
4 Years ago
;