Skip to content

Instantly share code, notes, and snippets.

@fahimbabarpatel
Last active September 30, 2015 14:14
Show Gist options
  • Save fahimbabarpatel/de914ba1d3cab7c0e0ec to your computer and use it in GitHub Desktop.
Save fahimbabarpatel/de914ba1d3cab7c0e0ec to your computer and use it in GitHub Desktop.
Sort JavaScript Object(hash) by value.
var res = [{"s1":5},{"s2":3},{"s3":8}].sort(function(obj1,obj2){ 
 var prop1;
 var prop2;
 for(prop in obj1) {
  prop1=prop;
 }
 for(prop in obj2) {
  prop2=prop;
 }
 //the above two for loops will iterate only once because we use it to find the key
 //return obj1[prop1]-obj2[prop2];
 return obj2[prop2]-obj1[prop1];
});

res will have the result array

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment