Targeting Specific Objects in an Array
Filtering an array of objects based on a different array can be useful in various scenarios. Consider a scenario where we have an array of people objects and an additional array containing specific identifiers (e.g., IDs).
Given an array of people:
const people = [ { id: "1", name: "abc", gender: "m", age: "15" }, { id: "2", name: "a", gender: "m", age: "25" }, { id: "3", name: "efg", gender: "f", age: "5" }, { id: "4", name: "hjk", gender: "m", age: "35" }, { id: "5", name: "ikly", gender: "m", age: "41" }, { id: "6", name: "ert", gender: "f", age: "30" }, { id: "7", name: "qwe", gender: "f", age: "31" }, { id: "8", name: "bdd", gender: "m", age: "78" } ];
and an array of desired IDs:
const id_filter = [1, 4, 5, 8];
Filtering Objects Using Array.filter
To filter the array of people based on the provided IDs, we can employ the array's filter() method. This method accepts a callback function that receives each element of the array and returns a Boolean value. To cater to our filtering needs, we define our callback function as follows:
person => id_filter.includes(person.id)
This callback function essentially checks whether the current person's ID is present in the id_filter array. If found, it returns true; otherwise, it returns false.
Utilizing this callback function, we can now filter our array of people:
const filteredPeople = people.filter(person => id_filter.includes(person.id));
The resulting filteredPeople array will contain only those objects from the original array whose IDs match the values in id_filter.
The above is the detailed content of How to Filter an Array of Objects Based on IDs from Another Array?. For more information, please follow other related articles on the PHP Chinese website!