包含对象的两个数组的差异和交集 [英] Difference and intersection of two arrays containing objects

查看:261
本文介绍了包含对象的两个数组的差异和交集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数组 list1 list2 ,其中包含具有某些属性的对象; userId 是Id或唯一属性:

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 应该返回元素的交集:

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

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


  • list1 operation list2 应该返回列表来自 list1 list2中没有出现

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


  • list2操作list1 应该返回 list2 中的元素列表,它们不会出现在 list1 中:

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

    这篇关于包含对象的两个数组的差异和交集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆