Difference and intersection of two arrays containing objects

后端 未结 7 836
予麋鹿
予麋鹿 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:54
    function intersect(first, second) {
        return intersectInternal(first, second, function(e){ return e });
    }
    
    function unintersect(first, second){
        return intersectInternal(first, second, function(e){ return !e });  
    }
    
    function intersectInternal(first, second, filter) {
        var map = {};
    
        first.forEach(function(user) { map[user.userId] = user; });
    
        return second.filter(function(user){ return filter(map[user.userId]); })
    }
    
    0 讨论(0)
提交回复
热议问题