Home > Web Front-end > JS Tutorial > How to Filter an Array of Objects Based on IDs from Another Array?

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

Barbara Streisand
Release: 2024-12-10 20:04:11
Original
728 people have browsed it

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

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" }
];
Copy after login

and an array of desired IDs:

const id_filter = [1, 4, 5, 8];
Copy after login

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)
Copy after login

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));
Copy after login

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template