Is there a method to check if two object arrays have any common elements, and if so, find the intersecting object? Similar to a Contains function. For instance, in the provided example, ProductId3 in Object Array 1 is also present in Object Array 2.
I'm considering using a nested loop, but I'm wondering if there is a more efficient or concise way to achieve this, perhaps using an ECMA or lodash function.
Note: We are comparing all object attributes, not just ProductId.
array1.forEach(arr1 => {
array2.forEach(arr2 => {
if (arr1.productId === arr2.productId &&
arr1.productName === arr2.productName ...)
Object Array 1:
[
{
ProductId: 50,
ProductName: 'Test1',
Location: 77,
Supplier: 11,
Quantity: 33
},
{
ProductId: 3,
ProductName: 'GHI',
Location: 1,
Supplier: 4,
Quantity: 25
}
]
Object Array 2:
[
{
ProductId: 1,
ProductName: 'ABC',
Location: 3,
Supplier: 4,
Quantity: 52
},
{
ProductId: 2,
ProductName: 'DEF',
Location: 1,
Supplier: 2,
Quantity: 87
},
{
ProductId: 3,
ProductName: 'GHI',
Location: 1,
Supplier: 4,
Quantity: 25
},
{
ProductId: 4,
ProductName: 'XYZ',
Location: 5,
Supplier: 6,
Quantity: 17
}
]
Resources:
How to determine if Javascript array contains an object with an attribute that equals a given value?
Javascript: Using `.includes` to find if an array of objects contains a specific object