9

I've got a jquery json request and in that json data I want to be able to sort by unique values. so I have

{
  "people": [{
        "pbid": "626",
        "birthDate": "1976-02-06",
        "name": 'name'
      }, {
        "pbid": "648",
        "birthDate": "1987-05-22",
        "name": 'name'
      }, .....

So, far, i have this

function(data) {
  $.each(data.people, function(i, person) {
    alert(person.birthDate);
  })
}

but, I am at a total loss as to how efficiently get only the unique birthDates, and sort them by year (or any sort by any other personal data).

I'm trying to do this, and be efficient about it (i'm hoping that is possible).

Thanks

1
  • I see this all the time. instead of using function(i, person) alert(person.birthDate) use function() alert(this.birthDate) Commented Feb 5, 2009 at 19:38

3 Answers 3

10

I'm not sure how performant this will be, but basically I'm using an object as a key/value dictionary. I haven't tested this, but this should be sorted in the loop.

function(data) {
    var birthDates = {};
    var param = "birthDate"
    $.each(data.people, function() {
        if (!birthDates[this[param]])
            birthDates[this[param]] = [];   
        birthDates[this[param]].push(this);
    });

    for(var d in birthDates) {
        // add d to array here
        // or do something with d
        // birthDates[d] is the array of people
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Wow, that's awesome, and gets me most (or alot) of the way there, but what I'm still stuck with is once I have the uniques in an array, how can I query for the persons name using that? I'm basically trying to say get name where birthDate=d?
thanks bendeweay. This works, but I was actually hoping there was a nicer way of doing this with json, so that i could easily sort by another variable later, without recreating a new array. Oh well, this definitely works. Thanks Pete
Not exactly perfect, but you can supply the birthDate as a variable if you want. I updated my sample
7
function(data){
    var arr = new Array();
    $.each(data.people, function(i, person){
        if (jQuery.inArray(person.birthDate, arr) === -1) {
            alert(person.birthDate);
            arr.push(person.birthDate);
        }
    });
}

Comments

4

Here's my take:

function getUniqueBirthdays(data){
    var birthdays = [];
    $.each(data.people, function(){
        if ($.inArray(this.birthDate,birthdays) === -1) {
            birthdays.push(this.birthDate);
        }
    });
    return birthdays.sort();
}

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.