0

I wrote this up today and it is working fine, however, I noticed the capitalization is taking preference in the sorting... how can I go about sorting this case insensitive while preserving the original strings?

// original data
var data = 'keyword,another,test,546,Hello';

//if keywords then split them by comma into an array
var keyArray = new Array();
keyArray = data.split(",");

// sort the new array alpha
keyArray.sort();

// now output as nice display
var keyOut = '';
var keyLength = keyArray.length;
for (var i = 0; i < keyLength; i++) {
    //create output
    var keyOut = keyOut.concat('<span class="label label-default">'+keyArray[i]+'</span> ');
}

return keyOut;

EDIT :

Answered my own after finding a quick example and working as expected...

keyArray.sort(function (a, b) {
    return a.toLowerCase().localeCompare(b.toLowerCase());
});
user756659
  • 3,372
  • 13
  • 55
  • 110
  • 1
    If I'm correct you can supply a custom sort function to `sort`: `.sort(function(a,b){return a.toLowerCase() < b.toLowerCase();})` – Koen. Feb 25 '14 at 21:49
  • 1
    http://stackoverflow.com/questions/8996963/how-to-perform-case-insensitive-sorting-in-javascript – dkasipovic Feb 25 '14 at 21:49
  • Just found an example and it appears to be working as expected... I edited my OP. Thanks. – user756659 Feb 25 '14 at 21:50
  • 1
    I believe `localeCompare` is much slower than string comparison. But on a small dataset this probably doesn't matter. – Koen. Feb 25 '14 at 21:54

1 Answers1

0

You can do something like this:

// original data
var data = 'keyword,another,test,546,Hello';

//if keywords then split them by comma into an array
var keyArray = new Array();
keyArray = data.split(",");

// sort the new array
keyArray.sort(function(a, b) {
        var textA = a.toUpperCase();
        var textB = b.toUpperCase();
        return (textA < textB) ? -1 : (textA > textB) ? 1 : 0;
    });

// now output as nice display
var keyOut = '';
var keyLength = keyArray.length;
for (var i = 0; i < keyLength; i++) {
    //create output
    var keyOut = keyOut.concat('<span class="label label-default">'+keyArray[i]+'</span> ');
}

return keyOut;
daniil.t
  • 490
  • 2
  • 9