Skip to content

Instantly share code, notes, and snippets.

@ashking
Created February 18, 2015 10:02
Show Gist options
  • Save ashking/5d300f77492aee58839e to your computer and use it in GitHub Desktop.
Save ashking/5d300f77492aee58839e to your computer and use it in GitHub Desktop.
Compare and diff two array of objects
//Requires underscores.js
//Verbose:
var a = [{'id':1, 'value':10}, {'id':2, 'value':20}];
var b = [{'id':1, 'value':10}, {'id':4, 'value':40}];
var arr1 = _.pluck(a, "id");
var arr2 = _.pluck(b, "id");
var diff = _.difference(arr1, arr2);
var result = _.filter(a, function(obj) {
return diff.indexOf(obj.id) >= 0;
});
//Concisely:
var diff = _.difference(_.pluck(a, "id"), _.pluck(b, "id"));
var result = _.filter(a, function(obj) { return diff.indexOf(obj.id) >= 0; });
//Outputs
{
id: 2
value: 20
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment