Home > Web Front-end > JS Tutorial > How Can I Filter a JavaScript Object Array Based on Multiple Attributes?

How Can I Filter a JavaScript Object Array Based on Multiple Attributes?

Patricia Arquette
Release: 2024-12-29 13:54:09
Original
256 people have browsed it

How Can I Filter a JavaScript Object Array Based on Multiple Attributes?

Filtering Object Array Based on Attributes

To filter a given array of objects based on specific attributes, you can utilize the Array.prototype.filter method in JavaScript. This powerful method allows you to create a new array containing only the elements that meet your specified criteria.

For instance, you have an array of real estate home objects and want to return a subset of homes based on their price, square footage, number of beds, and number of baths.

To achieve this, you can use the filter method as follows:

var newArray = homes.filter(function (el) {
  return el.price <= 1000 &&
         el.sqft >= 500 &&
         el.num_of_beds >= 2 &&
         el.num_of_baths >= 2.5;
});
Copy after login

In this example:

  • The filter method iterates over each object in the 'homes' array.
  • For each object, it checks if all of the criteria are met using the specified logical operators (&&).
  • If an object meets all the conditions, it is included in the 'newArray'.

You can modify the criteria to filter based on your specific requirements. For example, to find homes with a price under $1000, square footage over 500, at least two beds, and at least 1.5 baths, you would use the following criteria:

el.price <= 1000 &&
el.sqft >= 500 &&
el.num_of_beds >= 2 &&
el.num_of_baths >= 1.5;
Copy after login

This code will filter the 'homes' array and return only the objects that satisfy these criteria, creating a new array with the filtered results.

The above is the detailed content of How Can I Filter a JavaScript Object Array Based on Multiple Attributes?. 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