Filter Array of Objects Based on Another Array of Objects
Problem:
Given two arrays of objects, the goal is to filter the first array based on a specific criterion using the second array as reference. Specifically, we want to filter the first array to include only those objects that match specific properties (userid and projectid) with objects in the second array.
Solution:
utilizing the filter and some methods in the array, we can achieve the following solution:
Example:
<code class="js">const myArray = [{ userid: "100", projectid: "10", rowid: "0" }, { userid: "101", projectid: "11", rowid: "1" }, { userid: "102", projectid: "12", rowid: "2" }, { userid: "103", projectid: "13", rowid: "3" }, { userid: "101", projectid: "10", rowid: "4" }]; const myFilter = [{ userid: "101", projectid: "11" }, { userid: "102", projectid: "12" }, { userid: "103", projectid: "11" }]; const myArrayFiltered = myArray.filter((el) => { return myFilter.some((f) => { return f.userid === el.userid && f.projectid === el.projectid; }); }); console.log(myArrayFiltered);</code>
Expected result:
<code class="js">[ { userid: "101", projectid: "11", rowid: "1" }, { userid: "102", projectid: "12", rowid: "2" } ]</code>
The above is the detailed content of How to Filter an Array of Objects Based on Another Array of Objects?. For more information, please follow other related articles on the PHP Chinese website!