Created
February 18, 2015 10:02
-
-
Save ashking/5d300f77492aee58839e to your computer and use it in GitHub Desktop.
Compare and diff two array of objects
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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