Sunday, November 21, 2010

JQuery, Javascript: How to sort string arrays by length and alphabetically

If you have an array that contains strings like this-one:

var myArray = ['120', '230', '60', '50', '50A', '50B', '120AB', '35C'];


to sort it by length and alphabetically you can use a custom sorting function:

function length_alpha_sort(astr, bstr) {
 if (astr.length != bstr.length) {
  return astr.length - bstr.length;
 }
 return (astr < bstr) ? -1 : (astr > bstr) ? 1 : 0;
};


After calling the sort function on myArray its content becomes:

myArray.sort(length_alpha_sort);
alert(myArray); // prints 50, 60, 120, 230, 35C, 50A, 50B, 120AB


If the array can contain both strings and numbers the custom sort function should be modified as follows:

function length_alpha_sort2(astr, bstr) {
 astr += '';
 bstr += '';
 if (astr.length != bstr.length) {
  return astr.length - bstr.length;
 }
 return (astr < bstr) ? -1 : (astr > bstr) ? 1 : 0;
};


example:

var myArray = [1500, '120', '230', '60', '50', '50A', 33, '50B', '120AB', '35C'];
myArray.sort(length_alpha_sort2);
alert(myArray); // prints 33, 50, 60, 120, 230, 35C, 50A, 50B, 1500, 120AB

No comments: