How to merge two arrays of JSON objects - removing duplicates and preserving order in Javascript/jQuery?

后端 未结 4 698
自闭症患者
自闭症患者 2020-12-29 12:38

jsfiddle link: http://jsfiddle.net/vN6fn/1/

Assume I have these 2 objects:

var obj1 = { data: [ 
                      {id:1, commen         


        
4条回答
  •  清酒与你
    2020-12-29 13:13

    You can use $.merge and then go through and remove duplicates, and then sort it.

    $.merge(obj1.data, obj2.data);
    
    var existingIDs = [];
    obj1.data = $.grep(obj1.data, function(v) {
        if ($.inArray(v.id, existingIDs) !== -1) {
            return false;
        }
        else {
            existingIDs.push(v.id);
            return true;
        }
    });
    
    obj1.data.sort(function(a, b) {
        var akey = a.id, bkey = b.id;
        if(akey > bkey) return 1;
        if(akey < bkey) return -1;
        return 0;
    });
    

提交回复
热议问题