Skip to content

Instantly share code, notes, and snippets.

@scarstens
Created July 15, 2013 20:45
Show Gist options
  • Select an option

  • Save scarstens/6003301 to your computer and use it in GitHub Desktop.

Select an option

Save scarstens/6003301 to your computer and use it in GitHub Desktop.
Sort array of objects by a property in each object
function sortObjectBy(property) {
var sortOrder = 1;
if(property[0] === "-") {
sortOrder = -1;
property = property.substr(1, property.length - 1);
}
return function (a,b) {
var result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0;
return result * sortOrder;
}
}
/* Example usage: */
var distances = [];
distances.push({marker:'Arizona', distance: 300})
distances.push({marker:'Utah', distance: 100})
distances.push({marker:'Washington', distance: 600})
distances.push({marker:'California', distance: 200})
distances.sort(sortObjectBy("distance"));
console.log(distances);
/* Note they are now sorted by distance instead of the order above. */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment