i'm trying to do a javascript filter to an array but somehow im returning one array when it needs to be separated (0 first data 1 second data) so that I can process it easily in a another loop. I hope the below makes sense. Thank you in advance for any help.
JSON INPUT
[
{
"id": 1,
"title": "Ford F-150",
"type": "truck"
},
{
"id": 2,
"title": "BMW 4 series",
"type": "car"
},
{
"id": 3,
"title": "Triumph Scrambler",
"type": "motorbike"
},
{
"id": 4,
"title": "Audi A3",
"type": "car"
}
]
INTO data ARRAY THE FILTERED
function filterByProperty(array, prop, value){
var filtered = [];
for (var i = 0; i < array.length; i++) {
var obj = array[i];
for (var key in obj) {
if (typeof(obj[key] === "object")) {
var item = obj[key];
if(obj[prop] == value){
filtered.push(item);
}
} else {
console.log("not object");
}
}
}
return filtered;
}
var filtereddata = filterByProperty(data, "type", "car");
console.log(filtereddata);
When I run this, I only see one array not two?
filtermethod available on arrays. You don't seem to need 2 different arrays, just one with objects that match a certain criterion, namely thetypevalue of specific objects within the array you're filtering.