Wednesday, October 23, 2019

Sorting by Key in An Array of object with Jquery

var data = [{ TagId: 1, TagName: "C#", }, 
{ TagId: 2, TagName: "Single Page Application", }, 
{ TagId: 3, TagName: "Visual Studio", }, 
{ TagId: 4, TagName: "Fakes", }]

var posts = [];
    posts = sortByKeyDesc(data, "TagId");


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 : ((x > y) ? 1 : 0));
        });
    }

No comments:

Post a Comment

Your feedback is always appreciated. I will try to reply to your queries as soon as time allows.Please don't spam,spam comments will be deleted upon reviews.