Home >Web Front-end >JS Tutorial >How to Filter a JavaScript Array of Objects Based on IDs and a Specific Condition?
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:
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>
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:
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!