Home > Web Front-end > JS Tutorial > How to Filter a JavaScript Object Array Based on Another Array and a Specific Attribute?

How to Filter a JavaScript Object Array Based on Another Array and a Specific Attribute?

Mary-Kate Olsen
Release: 2024-12-09 02:02:11
Original
745 people have browsed it

How to Filter a JavaScript Object Array Based on Another Array and a Specific Attribute?

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

In this implementation:

  • people.filter() creates a new array containing only the objects that pass the callback function's filter.
  • The callback function, represented by the arrow function (person => ...), takes an object person as input and evaluates whether it meets the defined criteria.
  • The expression id_filter.includes(person.id) checks if the object's id property exists in the id_filter array.
  • The condition person.gender === "m" ensures that only objects with the "gender" attribute set to "m" are included.

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!

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