Home > Web Front-end > JS Tutorial > body text

How to Filter an Array of Objects Based on Matching Properties with Another Array of Objects?

Patricia Arquette
Release: 2024-10-30 23:41:29
Original
989 people have browsed it

How to Filter an Array of Objects Based on Matching Properties with Another Array of Objects?

Filtering Array of Objects with Another Array of Objects

Consider the following arrays of objects:

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"
}
...]
Copy after login

myFilter:

[
{
    userid: "101", 
    projectid: "11"
}, 
{
    userid: "102", 
    projectid: "12"
},
{
    userid: "103",
    projectid: "11"
}]
Copy after login

The goal is to filter myArray using myFilter such that only objects in myArray that have matching userid and projectid values with the objects in myFilter are included in the filtered array.

Solution:

We can employ the filter and some array methods to achieve this filtering:

<code class="javascript">const myArrayFiltered = myArray.filter((el) => {
  return myFilter.some((f) => {
    return f.userid === el.userid &amp;&amp; f.projectid === el.projectid;
  });
});</code>
Copy after login

Explanation:

  • The filter method iterates over each element in myArray.
  • For each element, the some method is used to check if there exists an element in myFilter where both the userid and projectid values match the current element.
  • If such a match is found for any element in myFilter, the current element from myArray is included in the myArrayFiltered array.
  • Otherwise, it is excluded.

The above is the detailed content of How to Filter an Array of Objects Based on Matching Properties with Another Array of Objects?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!