Home >Web Front-end >JS Tutorial >How to Filter a JavaScript Array of Objects by ID and Gender?

How to Filter a JavaScript Array of Objects by ID and Gender?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-10 14:34:10996browse

How to Filter a JavaScript Array of Objects by ID and Gender?

Filtering Array of Objects Based on Another Array in JavaScript

Given two arrays, one containing objects and the other containing a list of IDs, a common task is to filter the object array to include only objects with IDs matching those in the filter array. However, in this case, we have an additional criterion to filter by gender, specifically selecting male ("m") individuals.

Solution:

To achieve this filtering operation, we can utilize the filter() method on the people array. This method accepts a callback function as an argument, which takes an individual object and returns a boolean value indicating whether the object should be included in the filtered array. For our purpose, the filtering criteria are based on matching IDs and the gender being male. This leads us to the following filtering function:

By incorporating this filtering function into our filter() call, we obtain the following code:

This code will return a new array, filteredPeople, containing only objects from the original people array that have IDs matching those in the id_filter array and are of the male gender.

The above is the detailed content of How to Filter a JavaScript Array of Objects by ID and Gender?. 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