Krishh
Krishh

Reputation: 4231

Get Unique values for json Data using jquery

I have my json data as follows:

var Data = [{"Name":"a1","ID":"b1", "year":"2011"}, 
{"Name":"a2", "ID":"b2", "year":"2012"}, 
{"Name":"a3", "ID":"b3", "year":"2012"},
{"Name":"a4", "ID":"b4", "year":"2010"}];

I need to display the data as follows,

2012
a2   b2
a3   b3

2011
a1   b1

2010
a4   b4

This is what I have tried: To get unique values

var uniqueGroups = {};
            $.each(Data, function () {
uniqueGroups[this.year] = this.year;
});

 $.each(uniqueGroups, function (g) {
                resultsdiv.append('<p>' + g +'</p>' );
                $.each(json.Data, function (i, memDetails) {
                    if (memDetails.year == g) {
                        resultsdiv.append('<div>' + memDetails.Name + memDetails.ID +'</div>');
                    }
                });
            });

This prints out the results but in ascending order, But I would require it to be in descending order. How can I approach this? (Even if I sort the json on the server, it is returning in ascending order)

Upvotes: 0

Views: 4141

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

var uniqueGroups = [];
$.each(json.Data, function () {
    var year = parseInt(this.year);
    if (uniqueGroups.indexOf(year) < 0) {
        uniqueGroups.push(year);
    };
});
uniqueGroups.sort(function(x, y) { return x < y; });

$.each(uniqueGroups, function (index, year) {
    resultsdiv.append('<p>' + year.toString() + '</p>');
    $.each(Data, function (i, memDetails) {
        if (memDetails.year == year.toString()) {
            resultsdiv.append('<div>' + memDetails.Name + memDetails.ID + '</div>');
        }
    });
});
​

Upvotes: 3

Related Questions