To find the intersection of an array of objects in JavaScript, you need to compare the objects based on certain properties. One approach to do this is to use the reduce()
method and filter()
method.
Here is an example:
let arr1 = [{ id: 1, name: "John" }, { id: 2, name: "Jane" }, { id: 3, name: "Jim" }];
let arr2 = [{ id: 2, name: "Jane" }, { id: 3, name: "Jim" }, { id: 4, name: "Joe" }];
let result = arr1.reduce((acc, curr) => {
if (arr2.find(e => e.id === curr.id)) {
acc.push(curr);
}
return acc;
}, []);
console.log(result); // Output: [{ id: 2, name: "Jane" }, { id: 3, name: "Jim" }]
In this example, arr1
and arr2
are two arrays of objects. The reduce()
method is used to loop through arr1
and check if the current object is present in arr2
using the find()
method. If the object is found, it is pushed to the accumulator array acc
. Finally, the accumulator array is returned as the result of the function.
+ There are no comments
Add yours