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

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

DDD
Release: 2024-11-02 03:34:30
Original
481 people have browsed it

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

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:

  1. First Array Iteration:
    Use the filter method on the first array to iterate over each element.
  2. Match Check:
    Inside the filter callback function, use the some method on the second array to check if there is an object that matches the current element of the first array based on the userid and projectid properties.
  3. Filtering:
    If there is a match, the some function will return true, which will retain that element in the filtered result array.

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

Expected result:

<code class="js">[
  { userid: "101", projectid: "11", rowid: "1" },
  { userid: "102", projectid: "12", rowid: "2" }
]</code>
Copy after login

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!

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
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!