Home >Web Front-end >JS Tutorial >How to Filter a JavaScript Array of Objects Based on IDs and a Specific Condition?

How to Filter a JavaScript Array of Objects Based on IDs and a Specific Condition?

DDD
DDDOriginal
2024-12-10 17:57:10513browse

How to Filter a JavaScript Array of Objects Based on IDs and a Specific Condition?

Filtering an Array of Objects Based on Another Array and Specific Criteria in JavaScript

Given an array of objects and a second array containing specific IDs, the task is to filter the first array to include only objects that match the specified IDs and satisfy an additional condition.

Consider the following scenario:

  • Array people:
    people = [<br>  {id: "1", name: "abc", gender: "m", age:"15"},<br>  {id: "2", name: "a", gender: "m", age:"25"},<br>  {id: "3", name: "efg", gender: "f", age:"5"},<br>  {id: "4", name: "hjk", gender: "m", age:"35"},<br>  {id: "5", name: "ikly", gender: "m", age:"41"},<br>  {id: "6", name: "ert", gender: "f", age:" 30"},<br>  {id: "7", name: "qwe", gender: "f", age:" 31"},<br>  {id: "8", name: "bdd", gender: "m", age:" 78"},<br>]<br>
  • Array of target IDs:
    id_filter = [1,4,5,8]<br>

To retrieve objects from people that match the IDs in id_filter and have a specific gender, we can employ the filter() function in JavaScript:

const filteredPeople = people.filter(person => id_filter.includes(person.id) && person.gender === "m");

By combining the includes() method to check for ID matches and the strict equality operator (===) to verify the gender, we obtain the desired result:

  • Verify if the object's id is present in id_filter.
  • Check if the object's gender value matches the specified condition (in this case, "m" for male).

The resulting filteredPeople array will contain only objects that meet both criteria, providing the filtered data based on the input arrays.

The above is the detailed content of How to Filter a JavaScript Array of Objects Based on IDs and a Specific Condition?. 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