Filtering an Object Array Based on Another Array in JavaScript
This task requires filtering an array of objects to extract specific target objects based on their IDs. Given an array of objects (people) and an array of desired IDs (id_filter), our goal is to return a subset of people that matches the target IDs and have a specific attribute, in this case "gender: "m"".
Solution:
The most efficient approach to filter the array is by employing the filter() function. The filter() function takes a callback function that determines whether an object in the array will be included in the filtered result. We can construct a callback function that checks if the object's id property is present in the id_filter array. Additionally, we can add a condition to filter based on the "gender" attribute.
Here's the implementation:
const filteredPeople = people.filter(person => id_filter.includes(person.id) && person.gender === "m");
In this implementation:
The resulting filteredPeople array contains the objects from the original people array that have the specified IDs and matching gender.
The above is the detailed content of How to Filter a JavaScript Object Array Based on Another Array and a Specific Attribute?. For more information, please follow other related articles on the PHP Chinese website!