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

Thursday, November 18, 2010

JQuery: How to count elements in an object

Function to count elements in an object using jquery:
var myObj = {
    1: {  44:  ['18',  'anna'],  55:  ['19',  'ina'],  66:  ['19',  'dina']  },
    2: {  11:  ['21', 'maria'],  33:  ['20',  'olga']  }
};

function object_counter(obj)
{
    var count = 0;
    $.each(obj, function(){
        ++count;
    });
    return count;
};

var cnt = object_counter(myObj); // cnt is 2