0

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.

2 Answers 2

3

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)

Sign up to request clarification or add additional context in comments.

3 Comments

Elegant answer, short and nice.
This'll work, but .filter() just treats the return value as a boolean, so you could just return the result of the .indexOf() test.
thanks..got me there. I actually wanted the items that don't match, so if(simpleArray.indexOf(item.id) == -1).
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.

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"} ]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.