simnom of ifour
4/20/2016 - 4:22 PM

Sort Objects In Array By Key

Sort Objects In Array By Key

function dynamicSort(property) {
    var sortOrder = 1;
    if(property[0] === "-") {
        sortOrder = -1;
        property = property.substr(1);
    }
    return function (a,b) {
        var result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0;
        return result * sortOrder;
    }
}

var unsortedArray = [
    {keyToSortBy:'me', anotherKey:'that'},
    {keyToSortBy:'you', anotherKey:'example'},
    {keyToSortBy:'you', anotherKey:'words'},
    {keyToSortBy:'me', anotherKey:'in'},
    {keyToSortBy:'me', anotherKey:'here'},
];
var sortedArray = unsortedArray.sort(dynamicSort('keyToSortBy'));