tags:

views:

2006

answers:

3

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

+4  A: 

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
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 sayget name where birthDate=d?
pedalpete
updated to include your requested update
bendewey
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. ThanksPete
pedalpete
Not exactly perfect, but you can supply the birthDate as a variable if you want. I updated my sample
bendewey
+1  A: 
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  A: 

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