Home > Web Front-end > JS Tutorial > How Can I Filter a JavaScript Array of Objects Based on Specific Attributes?

How Can I Filter a JavaScript Array of Objects Based on Specific Attributes?

DDD
Release: 2024-12-25 00:52:10
Original
222 people have browsed it

How Can I Filter a JavaScript Array of Objects Based on Specific Attributes?

Filtering an Array of Objects Based on Attributes

This article aims to demonstrate how to filter an array of objects based on specific attributes in JavaScript. To illustrate the concept, we'll use a hypothetical array of real estate home objects as an example.

The provided object array contains multiple homes with attributes such as price, square footage, number of beds, and number of baths. The goal is to create a new array containing only homes that meet certain criteria, such as:

  • Price less than or equal to 1000
  • Square footage greater than or equal to 500
  • Number of beds greater than or equal to 2
  • Number of baths greater than or equal to 2.5

To achieve this, we can utilize the JavaScript Array.prototype.filter method. Here's an example of how the code would look like:

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 code:

  • The filter method iterates through each element of the homes array.
  • For each element, it executes the provided callback function, which takes an individual home object as an argument.
  • Within the callback function, we apply the specified criteria by checking conditions for price, square footage, number of beds, and number of baths using logical operators.
  • If all conditions are met for a particular home, it is included in the new array.

By executing this code, we will obtain an array (newArray) containing only homes that satisfy the specified criteria. This approach provides a flexible and efficient way to filter large arrays of objects based on custom attributes.

The above is the detailed content of How Can I Filter a JavaScript Array of Objects Based on Specific 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template