0

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)

2
  • In first place, why can't u sort and order the Collection on server by required field/property and then send it to the client side, since server side speeds are always good compared to client side? Commented Mar 2, 2012 at 13:25
  • Even if I sort it on the server, it is automatically presenting in ascending order. Commented Mar 2, 2012 at 13:26

1 Answer 1

3
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>');
        }
    });
});
​
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.