Home  >  Article  >  Web Front-end  >  How to Filter an Array of Objects Based on Matches with Another Array?

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

Barbara Streisand
Barbara StreisandOriginal
2024-11-01 08:39:02397browse

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

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 filter method iterates over myArray and creates a new array containing only the objects that satisfy the condition provided as an argument.
  • The some method, used within the condition, checks if any element in myFilter matches the userid and projectid properties of the current element in myArray.
  • If a match is found, the some method returns true, indicating that the current element should be included in the filtered array.

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!

Statement:
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