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:
list1 operation list2
should return the intersection of elements:
[
{ userId: 1235, userName: 'ABC' },
{ userId: 1236, userName: 'IJKL' }
]
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 operation list1
should return the list of elements from list2
which don't occur in list1
:
[
{ userId: 1252, userName: 'AAAA' }
]
question from:
https://stackoverflow.com/questions/33356504/difference-and-intersection-of-two-arrays-containing-objects 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…