Filter an Array of Objects with Another Array of Objects
Problem:
You want to filter an array of objects based on matches with a second array of objects. For instance, given the following arrays:
<code class="js">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" }, ]; myFilter = [ { userid: "101", projectid: "11" }, { userid: "102", projectid: "12" }, { userid: "103", projectid: "11" }, ];</code>
You need to filter myArray to only include objects where the userid and projectid properties match those in myFilter. The expected result is:
<code class="js">myArrayFiltered = [ { userid: "101", projectid: "11", rowid: "1" }, { userid: "102", projectid: "12", rowid: "2" }, ];</code>
Solution:
To filter the array, you can utilize the filter and some array methods:
<code class="js">const myArrayFiltered = myArray.filter((el) => { return myFilter.some((f) => { return f.userid === el.userid && f.projectid === el.projectid; }); });</code>
Explanation:
The above is the detailed content of How to Filter an Array of Objects Based on Matches with Another Array?. For more information, please follow other related articles on the PHP Chinese website!