Shashi Shashi - 1 month ago 13
AngularJS Question

javascript object array difference and intersection of elements

I have two arrays with javascript objects as list1 and list2 which has objects with some properties where 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 want a easiest way to where in


  1. list1 operation list2 returns me a result with the intersection of
    elements

    output should be [ {userId:1235,userName:'ABC'},
    {userId:1236,userName:'IJKL'}
    ]

  2. List item list1 operation list2 gives me list of all unintersected
    elements from list1

    output should be [ {userId:1234,userName:'XYZ'},
    {userId:1237,userName:'WXYZ'},
    {userId:1238,userName:'LMNO'}
    ]

  3. List item list2 operation list1 gives me unintersected elements from list2
    output should be [ {userId:1252,userName:'AAAA'} ]


Answer

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