Skip to content
Advertisement

How to filter object array based on attributes?

I have the following JavaScript array of real estate home objects:

JavaScript

What I would like to do is be able to perform a filter on the object to return a subset of “home” objects.

For example, I want to be able to filter based on: price, sqft, num_of_beds, and num_of_baths.

How can I perform something in JavaScript like the pseudo-code below:

JavaScript

Note, the syntax does not have to be exactly like above. This is just an example.

Advertisement

Answer

You can use the Array.prototype.filter method:

JavaScript

Live Example:

JavaScript

This method is part of the new ECMAScript 5th Edition standard, and can be found on almost all modern browsers.

For IE, you can include the following method for compatibility:

JavaScript
Advertisement