How to get the difference between two arrays with objects using underscore

I want to get the difference between two arrays i.e. array1 and array2.

Example:

Array1:[{Id:1,name:’ram’,age:10},{Id:2,name:’ram 1′,age:10},{Id:1,name:’ram 2′,age:10}]

Array2 :[{{Id:1,name:’ram 2′,age:10}]

Expected Output should be:[{Id:2,name:’ram 1′,age:10},{Id:1,name:’ram 2′,age:10}]

 

 

Solution : We can achieve this using underscore .

Step 1: We can uniquely differentiate two arrays with “Id” property,so i have plucked the Ids from two arrays using _.pluck and took the difference between this two arrays using _.difference and saved in diff object.

Step 2: Finally we can filter the array 1 with the difference object i.e. diff of the ids we got in step 1.
var diff = _.difference(_.pluck(Array1, “Id”), _.pluck(Array2, “Id”));
var finaldifferenceObject = _.filter(Array1, function (obj) { return diff.indexOf(obj.Id) >= 0; });

Advertisements

About alekhyakodamsharepoint

Hi.. I am alekhya working as a sharepoint developer.
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s