Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get distinct values from json in jquery

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

like image 580
pedalpete Avatar asked Feb 05 '09 19:02

pedalpete


2 Answers

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
    }
}
like image 180
bendewey Avatar answered Oct 12 '22 23:10

bendewey


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);
        }
    });
}
like image 40
jeremyasnyder Avatar answered Oct 13 '22 01:10

jeremyasnyder