I have the following JavaScript array of real estate home objects:
JavaScript
x
21
21
1
var json = {
2
'homes': [{
3
"home_id": "1",
4
"price": "925",
5
"sqft": "1100",
6
"num_of_beds": "2",
7
"num_of_baths": "2.0",
8
}, {
9
"home_id": "2",
10
"price": "1425",
11
"sqft": "1900",
12
"num_of_beds": "4",
13
"num_of_baths": "2.5",
14
},
15
// ... (more homes) ...
16
]
17
}
18
19
var xmlhttp = eval('(' + json + ')');
20
homes = xmlhttp.homes;
21
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
1
6
1
var newArray = homes.filter(
2
price <= 1000 &
3
sqft >= 500 &
4
num_of_beds >=2 &
5
num_of_baths >= 2.5 );
6
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
1
7
1
var newArray = homes.filter(function (el) {
2
return el.price <= 1000 &&
3
el.sqft >= 500 &&
4
el.num_of_beds >=2 &&
5
el.num_of_baths >= 2.5;
6
});
7
Live Example:
JavaScript
1
27
27
1
var obj = {
2
'homes': [{
3
"home_id": "1",
4
"price": "925",
5
"sqft": "1100",
6
"num_of_beds": "2",
7
"num_of_baths": "2.0",
8
}, {
9
"home_id": "2",
10
"price": "1425",
11
"sqft": "1900",
12
"num_of_beds": "4",
13
"num_of_baths": "2.5",
14
},
15
// ... (more homes) ...
16
]
17
};
18
// (Note that because `price` and such are given as strings in your object,
19
// the below relies on the fact that <= and >= with a string and number
20
// will coerce the string to a number before comparing.)
21
var newArray = obj.homes.filter(function (el) {
22
return el.price <= 1000 &&
23
el.sqft >= 500 &&
24
el.num_of_beds >= 2 &&
25
el.num_of_baths >= 1.5; // Changed this so a home would match
26
});
27
console.log(newArray);
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
1
19
19
1
if (!Array.prototype.filter) {
2
Array.prototype.filter = function(fun /*, thisp*/) {
3
var len = this.length >>> 0;
4
if (typeof fun != "function")
5
throw new TypeError();
6
7
var res = [];
8
var thisp = arguments[1];
9
for (var i = 0; i < len; i++) {
10
if (i in this) {
11
var val = this[i];
12
if (fun.call(thisp, val, i, this))
13
res.push(val);
14
}
15
}
16
return res;
17
};
18
}
19