0

I am a javascript beginner. I need to merge two arrays which contains objects which in turn contain arrays.

I have two arrays

arr1[
    {
        description : "this is a object",
        array       : [a.x,"b"]
     }
]

arr2[
    {
       array : [a.z,"b","c","d"]               
    } 
]

I have used the following code to perform the merge

function arrayUnique(array) {
    var a = array.concat();
    for(var i=0; i<a.length; ++i) {
        for(var j=i+1; j<a.length; ++j) {
            if(a[i] === a[j])
                a.splice(j--, 1);
        }
    }

    return a;
}
function combine(obj1,obj2) {
    var res = {};
    for (var k1 in obj1) {
        if (!obj1.hasOwnProperty(k1)) continue;
        if (obj2.hasOwnProperty(k1)) { // collision
            if (typeof(obj1[k1]) !== typeof(obj2[k1])) throw "type mismatch under key \""+k1+"\".";
            if (Array.isArray(obj1[k1])) {
                res[k1] = obj1[k1].concat(obj2[k1]);
            } else if (typeof(obj1[k1]) === 'string' || obj1[k1] instanceof String) {
                res[k1] = arrayUnique(obj1[k1].concat(obj2[k1]));
            } else if (typeof(obj1[k1]) === 'object') {
                res[k1] = combine(obj1[k1],obj2[k1]);
            } else {
                throw "unsupported collision type "+typeof(obj1[k1])+" under key \""+k1+"\".";
            }
        } else {
            res[k1] = obj1[k1];
        }
    }
    for (var k2 in obj2) {
        if (!obj2.hasOwnProperty(k2)) continue;
        if (obj1.hasOwnProperty(k2)) continue; // already handled it above
        res[k2] = obj2[k2];
    }
    return res;
}

var res = combine(arr1,arr2);

This is the result i expect

res = { description : "this is a object", array : [a.x,a.z,"b","c","d"] }

But unfortunately this is the result i get

res = { description : "this is a object", array : [a.x,"b","c","d"]}

a.z is ommited.

qualitytest
  • 763
  • 1
  • 10
  • 18

1 Answers1

0

When both objects have the same array field you concatenate them (concat append the two arrays one after another), here:

 if (Array.isArray(obj1[k1])) {
     res[k1] = obj1[k1].concat(obj2[k1]);

If instead of ["a","a","b","b","c","d"] you want to get ["a","b","c","d"] you need to perform the array merge manually.

Check this answer for multiple ways to merge arrays without duplicates.

uraimo
  • 19,081
  • 8
  • 48
  • 55
  • Thank you i was able to solve the duplication problem. But if my array has property of which the parent is same but the property is different then my merge does not seem to function properly. Request you to read my edited question. Could you please help. – qualitytest Aug 06 '15 at 11:43
  • What are a.x and a.z? If they are variables, arrayUnique checks only if they have the same value... what is the current value of a.x e a.z? – uraimo Aug 06 '15 at 11:47
  • Solved! Happy to help :) – uraimo Aug 06 '15 at 12:14