Sorting alphabetically with mixed case letters

When using JavaScript’s .sort() to sort an array of objects alphabetically, remember to set each string to lowercase or uppercase before you compare it. This will correct the priority that JavaScript gives capitalized letters over lowercase letters.

For example, instead of:

var defaultParent = $('.default-sort');
var defaultItems = defaultParent.children('li');
  
  defaultItems.sort(function(a, b) {
    x = a.getAttribute('data-sort');
    y = b.getAttribute('data-sort');
  
    if(x > y) {
      return 1;
    }
  
    if(x < y) {
      return -1;
    }
  
    return 0;
  });
  
  defaultItems.detach().appendTo(defaultParent);

You should use JavaScript’s .toLowerCase() or .toUpperCase() functions to get a true string comparison:

var lowerParent = $('.to-lower-sort');
var lowerItems = lowerParent.children('li');
  
  lowerItems.sort(function(a, b) {
    x = a.getAttribute('data-sort').toLowerCase();
    y = b.getAttribute('data-sort').toLowerCase();
  
    if(x > y) {
      return 1;
    }
  
    if(x < y) {
      return -1;
    }
  
    return 0;
  });
  
  lowerItems.detach().appendTo(lowerParent);

[codepen_embed height=”268″ theme_id=”0″ slug_hash=”VYjRdR” default_tab=”result” user=”aicarlson”]See the Pen Simple sorting with JavaScript by Andrew Carlson (@aicarlson) on CodePen.[/codepen_embed]

Leave a Reply

Your email address will not be published.