Monday, November 15, 2010

How to sort with JavaScript


var sort_by = function(field, reverse, primer){

   reverse = (reverse) ? -1 : 1;

   return function(a,b){

       a = a[field];
       b = b[field];

       if (typeof(primer) != 'undefined'){
           a = primer(a);
           b = primer(b);
       }

       if (a<b) return reverse * -1;
       if (a>b) return reverse * 1;
       return 0;

   }
}
// Sort by price high to low
homes.sort(sort_by('price', true, parseInt));
// Sort by city, case-insensitive, A-Z
homes.sort(sort_by('city', false, function(a){return a.toUpperCase()}));
You can also display warnings and alert windows:
<a HREF="javascript:window.alert('Invincibility is in oneself, vulnerability is in the opponent')">hey</a>
Another issue is, that < or > sign cannot be displayed and need to be replaced with &lt; and &gt; respectively.

No comments:

Post a Comment