Reputation: 41
I have an array that looks like this:
car1: 2
car2: 3
truck: 1
bike: 2
Now want to filter the array with jQuery grep to only see car elements.
var r = jQuery.grep(arr, function(a) {
return a.indexOf('car') === 0;
});
But my array is empty afterwards. What do I need to do in order to grep/filter the array correctly?
Upvotes: 1
Views: 746
Reputation: 11116
Depending on whether your data is actually an array of objects, or if it is a single object with multiple properties, here is a solution for each.
// solution for array of objects
var elems = [{car1: 2}, {car2: 3}, {truck: 1}, {bike: 2}];
var filtered = elems.reduce(function (result, current) {
var isCar = Object.keys(current).some(function (key){
return key.indexOf("car") > -1;
});
if (isCar) {
result.push(current);
}
return result;
}, []);
// returns an array of "car" objects
console.log(filtered)
// solution for single object with multiple properties
var elems2 = {car1: 2, car2: 3, truck: 1, bike: 2};
var filtered2 = Object.keys(elems2).reduce(function (result, current) {
var isCar = current.indexOf("car") > -1;
if (isCar) {
result[current] = elems2[current];
}
return result;
}, {});
// returns single object with only "car" properties and their values
console.log(filtered2)
Upvotes: 1