Wednesday, April 10, 2013

javascript 101: sort an array of maps by specific map key-value

Yesterday I posted about using jQuery to sort child elements via some field value. Today I had to go back to an even more basic question: a tidier way of sorting an array of hashes by the hash values for some particular key:

Javascript has a built in .sort() function for its arrays. (It tends to sort in place, so if you have something like
var x = [2,1,3];
var y = x.sort();
then both x and y are sorted.)

You can pass sort() a function(a,b) that should return -1, 0, or 1 based on whether a comes before or after b.

Other languages have a strcmp() function that returns those values for two strings, but in javascript you have to roll your own: (via http://phpjs.org/functions/strcmp/ )

function strcmp (str1, str2) {
  // http://kevin.vanzonneveld.net
  // +   original by: Waldo Malqui Silva
  // +      input by: Steve Hilder
  // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // +    revised by: gorthaur
  // *     example 1: strcmp( 'waldo', 'owald' );
  // *     returns 1: 1
  // *     example 2: strcmp( 'owald', 'waldo' );
  // *     returns 2: -1
  return ((str1 == str2) ? 0 : ((str1 > str2) ? 1 : -1)); 

}
or for shorter,
function strcmp (str1, str2) {  
   return ((str1 == str2) ? 0 : ((str1 > str2) ? 1 : -1)); 
}

so if you had an array of maps called users, and each map had a value for the key "name", the sort might look like
users.sort(function(a,b){ 
   return strcmp(a.name.toUpperCase(),b.name.toUpperCase());  
} );

No comments:

Post a Comment