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

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

Linda Hamilton
Release: 2024-11-02 08:50:02
Original
221 people have browsed it

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

Filtering Array of Objects Using Another Array of Objects

The task at hand is to filter an array of objects (myArray) based on a second array of objects (myFilter) to return only those objects in myArray whose userid and projectid properties match those in myFilter.

Solution

To achieve this, we utilize a combination of filter and some methods. The filter method iterates over each element in myArray and returns a new array containing only those elements that pass a given condition. In this case, the condition is satisfied if the element's userid and projectid match any of the userid and projectid pairs in myFilter.

The some method is used within the filter condition to determine whether any of the elements in myFilter meet the specified criteria. The condition checks whether the current myFilter element's userid and projectid properties are equal to those of the current myArray element. If a match is found, the some method returns true, indicating that the condition is met and the element should be included in the filtered array.

Code 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>
Copy after login

Output

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

The above is the detailed content of How to Filter an Array of Objects Based on Matching Properties in Another Array?. 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