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

Mickael Lherminez
  • 679
  • 1
  • 10
  • 29
pedalpete
  • 21,076
  • 45
  • 128
  • 239
  • I see this all the time. instead of using function(i, person) alert(person.birthDate) use function() alert(this.birthDate) – bendewey Feb 05 '09 at 19:38

3 Answers3

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
    }
}
bendewey
  • 39,709
  • 13
  • 100
  • 125
  • 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? – pedalpete Feb 05 '09 at 19:59
  • 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 – pedalpete Feb 05 '09 at 21:41
  • Not exactly perfect, but you can supply the birthDate as a variable if you want. I updated my sample – bendewey Feb 05 '09 at 21:50
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);
        }
    });
}
jeremyasnyder
  • 1,379
  • 1
  • 8
  • 8
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();
}
artlung
  • 33,305
  • 16
  • 69
  • 121