Difference and intersection of two arrays containing objects

后端 未结 7 893
予麋鹿
予麋鹿 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:41

    Just use filter and some array methods of JS and you can do that.

    let arr1 = list1.filter(e => {
       return !list2.some(item => item.userId === e.userId);
    });
    

    This will return the items that are present in list1 but not in list2. If you are looking for the common items in both lists. Just do this.

    let arr1 = list1.filter(e => {
       return list2.some(item => item.userId === e.userId); // take the ! out and you're done
    });
    

提交回复
热议问题