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; });
In this example:
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;
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!