shershams shershams - 4 months ago 19
jQuery Question

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

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

Assume I have these 2 objects:

var obj1 = { data: [
{id:1, comment:"comment1"},
{id:2, comment:"comment2"},
{id:3, comment:"comment3"}
] }

var obj2 = { data: [
{id:2, comment:"comment2"},
{id:3, comment:"comment3"},
{id:4, comment:"comment4"}
] }


And final object should look like this:

var final = { data: [
{id:1, comment:"comment1"},
{id:2, comment:"comment2"},
{id:3, comment:"comment3"},
{id:4, comment:"comment4"}
] }


Here are some things to consider:


  • obj1 and obj2 may or may not have duplicates



$.extend()
replaces objects,
$.merge()
doesn't remove duplicates (I know I can do for loop, but I'm looking for a better way to do this).

Answer

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;
});
Comments