且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

包含对象的两个数组的差异和交集

更新时间:2022-10-23 20:54:00

这是对我有用的解决方案.

 var intersect = function (arr1, arr2) {var intersect = [];_.each(arr1, 函数 (a) {_.each(arr2, 函数 (b) {如果(比较(a,b))intersect.push(a);});});返回相交;};var unintersect = function (arr1, arr2) {var unintersect = [];_.each(arr1, 函数 (a) {var 发现 = 假;_.each(arr2, 函数 (b) {如果(比较(a,b)){发现 = 真;}});如果(!找到){unintersect.push(a);}});返回不相交;};函数比较(a,b){如果(a.userId === b.userId)返回真;否则返回假;}

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' }
    ]
    

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