Sorting An Array of Objects

Example to sort array below using name property:

var arr = [
 {name: 'aaa', id: 1},
 {name: 'ccc', id: 3},
 {name: 'bbb', id: 2},
 {name: 'ddd', id: 4},
 ]

Below will be the methods to sort Asc/ Desc:

function sortByKeyDesc(array, key) {
        return array.sort(function (a, b) {
            var x = a[key]; var y = b[key];
            return ((x > y) ? -1 : ((x < y) ? 1 : 0));
        });
    }
function sortByKeyAsc(array, key) {
        return array.sort(function (a, b) {
            var x = a[key]; var y = b[key];
            return ((x  y) ? 1 : 0));
        });
    }

To call the method:

var sortArr = [];
sortArr = sortByKeyAsc(arr, "name");

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.