Merging two object arrays by removing duplicates Javascript Jquery

How to merge two object arrays with no two elements with same key 'id'?

var array1 = [{id:"1", expected:"aaa", actual:"xxx"}, {id:"2", expected:"bbb", actual:"yyy"}];
var array2 = [{id:"1", expected:"kkk", actual:"xxx"}, {id:"4", expected:"ccc", actual:"zzz"}];

And the result array should be,

var array3 = [{id:"1", expected:"kkk", actual:"xxx"}, , {id:"2", expected:"bbb", actual:"yyy"}, {id:"4", expected:"ccc", actual:"zzz"}];

The element with id "1" should be added from array2.

Answers 1

  • Try this..... First merge them , then remove duplicate

    $.merge(array1, array2);
    
    var existingIDs = [];
    array1 = $.grep(array1, function(v) {
        if ($.inArray(v.id, existingIDs) !== -1) {
            return false;
        }
        else {
            existingIDs.push(v.id);
            return true;
        }
    });
    

Related Articles