Howard Shaw
Howard Shaw

Reputation: 1071

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 return a new array with just the items from objArray where the id property value (1,2,3 etc) does not match an item in the simpleArray.

I should have returned:

result = [{id:2,name:'john'},{id:4,name:'pete'}]

I've tried various combinations of $.grep, .filter and $.inArray but struggling with this.

Upvotes: 0

Views: 530

Answers (2)

maerics
maerics

Reputation: 156534

@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.

function filterByMissingProp(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"} ]

Upvotes: 2

Christos
Christos

Reputation: 53958

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:

function Customer(id, name){
  this.id=id;
  this.name=name;
};

this.Customer.prototype.toString = function(){
  return "[id: "+this.id+" name: "+this.name+"]";
}

var objArray = [ new Customer(1,'fred'), new Customer(2,'john'), new Customer(3,'jane'), new Customer(4,'pete')];

var simpleArray = [1,3];

var results = [];

objArray.filter(function(item){
   
    if(simpleArray.indexOf(item.id)>-1)
        results.push(item);
});

document.write(results)

Upvotes: 3

Related Questions