scarstens
7/15/2013 - 8:45 PM

Sort array of objects by a property in each object

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. */