I agree about not reinventing the wheel, and just using the native Array filter method.
The function definition shown on the Mozilla page will add filter
if it's missing, regardless of the browser, by using object detection (if (!Array.prototype.filter)
)
Any of the methods suggesting eval
and/or multiple for
loops are both slow and potentially unsafe.
You didn't say so, but I'm assuming the values will be coming from user input (a form) so I'd do something like:
var filtered_results = obj.homes
.filter(function (home)
{
return parseInt(home.price) >= document.getElementsByName('price_gt')[0].value;
})
.filter(function (home)
{
return parseInt(home.price) <= document.getElementsByName('price_lt')[0].value;
})
.filter(function (home)
{
return parseFloat(home.num_of_baths) >= document.getElementsByName('baths_gt')[0].value;
});
better yet, don't iterate through the list N times and just do:
var filtered_results = obj.homes.filter(function (home)
{
return (
parseInt(home.price) >= document.getElementsByName('price_gt')[0].value &&
parseInt(home.price) <= document.getElementsByName('price_lt')[0].value &&
parseFloat(home.num_of_baths) >= document.getElementsByName('baths_gt')[0].value
);
});
I know this doesn't match the requested syntax but this approach is faster and more flexible (by not using eval or hardcoded values).