0

I need a relatively basic thing, which seems to confuse me quite a bit, and that is the difference between two lists, based on a certain property of a member object.

e.g.

var list1 = [{id:1, name:'John'}]
var list2 = [{id:1, name:'John'},{id:2, name:'Jack'},{id:3, name:'Daniel'}]

Wanted result, list3 = list2 - list1, based on the object's ID:

 var list3 = [{id:2, name:'Jack'},{id:3, name:'Daniel'}]

I know how to do this in C# LINQ, and that'd be:

 var list3 = list2.Where(x => !list1.Any(y => y.Id == x.Id));

But I need to this in js (and/or jQuery). Any help greatly appreciated.

iuliu.net
  • 6,666
  • 6
  • 46
  • 69
  • I'm a c# programmer too, have you considered something like Linq.js ? You will feel like home with it. – fradique Mar 02 '16 at 20:07

1 Answers1

0

You can use .filter for that purpose,

var list1 = [{id:1, name:'John'}]
var list2 = [{id:1, name:'John'},{id:2, name:'Jack'},{id:3, name:'Daniel'}]

var list3 = list2.filter(function(itm){ 
  var occurance = false; 
  list1.forEach(function(itm1){ if(itm.id == itm1.id) { 
   occurance = true; return; 
  });
  return !occurance;
});

DEMO

Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130