Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using underscore's “difference” method on arrays of objects

_.difference([], []) 

this method works fine when i'm having primitive type data like

var a = [1,2,3,4]; var b = [2,5,6]; 

and the _.difference(a,b) call returns [1,3,4]

but in case i'm using object like

var a = [{'id':1, 'value':10}, {'id':2, 'value':20}]; var b = [{'id':1, 'value':10}, {'id':4, 'value':40}]; 

doesn't seem to work

like image 355
Nas Avatar asked Oct 30 '12 20:10

Nas


People also ask

How will you differentiate between arrays and objects in JavaScript?

Both objects and arrays are considered “special” in JavaScript. Objects represent a special data type that is mutable and can be used to store a collection of data (rather than just a single value). Arrays are a special type of variable that is also mutable and can also be used to store a list of values.


1 Answers

try this on for size for finding the difference of an array of objects:

var test = [{a: 1},{b: 2}]; var test2 = [{a: 1}];  _.filter(test, function(obj){ return !_.findWhere(test2, obj); }); 
like image 87
kontr0l Avatar answered Sep 27 '22 23:09

kontr0l