Home >Web Front-end >JS Tutorial >How to Filter a Real Estate Home Object Array Based on Attributes?

How to Filter a Real Estate Home Object Array Based on Attributes?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-31 21:20:12870browse

How to Filter a Real Estate Home Object Array Based on Attributes?

Filter Object Array Based on Attributes

Problem:

You have an array of real estate home objects and want to filter them based on specific attributes, such as price, square footage, number of beds, and number of baths.

Solution:

To filter the array, you can utilize the Array.prototype.filter method.

Code:

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

Explanation:

The filter method takes a callback function that tests each element in the array. If the test returns true, the element is included in the new array. In this case, the callback function checks if the home object meets the specified criteria and returns true if it does.

Live Example:

var obj = {
    'homes': [{
            "home_id": "1",
            "price": "925",
            "sqft": "1100",
            "num_of_beds": "2",
            "num_of_baths": "2.0",
        }, {
            "home_id": "2",
            "price": "1425",
            "sqft": "1900",
            "num_of_beds": "4",
            "num_of_baths": "2.5",
        },
        // ... (more homes) ...     
    ]
};

// (Note that because `price` and such are given as strings in your object,
// the below relies on the fact that <= and >= with a string and number
// will coerce the string to a number before comparing.)

var newArray = obj.homes.filter(function(el) {
  return el.price <= 1000 &&
         el.sqft >= 500 &&
         el.num_of_beds >= 2 &&
         el.num_of_baths >= 1.5; // Changed this so a home would match
});

console.log(newArray);

The above is the detailed content of How to Filter a Real Estate Home Object Array Based on Attributes?. 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