vinnizworld
7/10/2012 - 12:04 PM

Function to sort array of objects by property name of each object

Function to sort array of objects by property name of each object

// Uses Prototype Inheritance

Array.prototype.sortByProp = function(p){
 return this.sort(function(a,b){
  return a[p] > b[p] ? 1 : a[p] < b[p] ? -1 : 0;
 });
}


/* Usage - Example */
objs = [{age:44,name:'vinay'},{age:24,name:'deepak'},{age:74,name:'suresh'}];

objs.sortByProp('age');
// Returns
// [{"age":24,"name":"deepak"},{"age":44,"name":"vinay"},{"age":74,"name":"suresh"}];

objs.sortByProp('name');
// Returns
// [{"age":24,"name":"deepak"},{"age":74,"name":"suresh"},{"age":44,"name":"vinay"}];