Search code examples
javascriptarraysset-intersectionset-differenceset-operations

Difference and intersection of two arrays containing objects


I have two arrays list1 and list2 which have objects with some properties; userId is the Id or unique property:

list1 = [
    { userId: 1234, userName: 'XYZ'  }, 
    { userId: 1235, userName: 'ABC'  }, 
    { userId: 1236, userName: 'IJKL' },
    { userId: 1237, userName: 'WXYZ' }, 
    { userId: 1238, userName: 'LMNO' }
]

list2 = [
    { userId: 1235, userName: 'ABC'  },  
    { userId: 1236, userName: 'IJKL' },
    { userId: 1252, userName: 'AAAA' }
]

I'm looking for an easy way to execute the following three operations:

  1. list1 operation list2 should return the intersection of elements:

    [
        { userId: 1235, userName: 'ABC'  },
        { userId: 1236, userName: 'IJKL' }
    ]
    
  2. list1 operation list2 should return the list of all elements from list1 which don't occur in list2:

    [
        { userId: 1234, userName: 'XYZ'  },
        { userId: 1237, userName: 'WXYZ' }, 
        { userId: 1238, userName: 'LMNO' }
    ]
    
  3. list2 operation list1 should return the list of elements from list2 which don't occur in list1:

    [
        { userId: 1252, userName: 'AAAA' }
    ]
    

Solution

  • This is the solution that worked for me.

     var intersect = function (arr1, arr2) {
                var intersect = [];
                _.each(arr1, function (a) {
                    _.each(arr2, function (b) {
                        if (compare(a, b))
                            intersect.push(a);
                    });
                });
    
                return intersect;
            };
    
     var unintersect = function (arr1, arr2) {
                var unintersect = [];
                _.each(arr1, function (a) {
                    var found = false;
                    _.each(arr2, function (b) {
                        if (compare(a, b)) {
                            found = true;    
                        }
                    });
    
                    if (!found) {
                        unintersect.push(a);
                    }
                });
    
                return unintersect;
            };
    
            function compare(a, b) {
                if (a.userId === b.userId)
                    return true;
                else return false;
            }