Difference and intersection of two arrays containing objects

后端 未结 7 872
予麋鹿
予麋鹿 2020-11-28 06:10

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

list1          


        
7条回答
  •  南方客
    南方客 (楼主)
    2020-11-28 06:43

    Here is a functionnal programming solution with underscore/lodash to answer your first question (intersection).

    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'}
            ];
    
    _.reduce(list1, function (memo, item) {
            var same = _.findWhere(list2, item);
            if (same && _.keys(same).length === _.keys(item).length) {
                memo.push(item);
            }
            return memo
        }, []);
    

    I'll let you improve this to answer the other questions ;-)

提交回复
热议问题