Find Items In Javascript Object Array Where One Of The Properties Does Not Match Items In Another Array
Say I have two arrays, one of objects, one simple: var objArray = [{id:1,name:'fred'},{id:2,name:'john'},{id:3,name:'jane'},{id:4,name:'pete'}] var simpleArray = [1,3] I want to
Solution 1:
You could try this one:
var results = [];
objArray.filter(function(item){
if(simpleArray.indexOf(item.id)>-1)
results.push(item);
})
Please try the following snippet:
functionCustomer(id, name){
this.id=id;
this.name=name;
};
this.Customer.prototype.toString = function(){
return"[id: "+this.id+" name: "+this.name+"]";
}
var objArray = [ newCustomer(1,'fred'), newCustomer(2,'john'), newCustomer(3,'jane'), newCustomer(4,'pete')];
var simpleArray = [1,3];
var results = [];
objArray.filter(function(item){
if(simpleArray.indexOf(item.id)>-1)
results.push(item);
});
document.write(results)
Solution 2:
@Christos' answer is good for many cases; however, if the simple array gets very large then the performance of that solution will degrade considerably (because it is doing a linear search instead of a constant-time lookup). Here is a solution that will perform well even when the simple array is very large.
functionfilterByMissingProp(objects, values, propertyName) {
var lookupTable = values.reduce(function(memo, value) {
memo[value] = true;
return memo;
}, {});
return objects.filter(function(object) {
return !(object[propertyName] in lookupTable);
});
}
var result = filterByMissingProp(objArray, simpleArray, 'id');
result; // => [ {id:2, name:"john"}, {id:4, name:"pete"} ]
Post a Comment for "Find Items In Javascript Object Array Where One Of The Properties Does Not Match Items In Another Array"