how to get distinct values from json in jquery

后端 未结 3 693
走了就别回头了
走了就别回头了 2020-12-31 15:13

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\",
           


        
相关标签:
3条回答
  • 2020-12-31 15:39

    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();
    }
    
    0 讨论(0)
  • 2020-12-31 15:50
    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);
            }
        });
    }
    
    0 讨论(0)
  • 2020-12-31 16:03

    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
        }
    }
    
    0 讨论(0)
提交回复
热议问题