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


_.difference([], []) 

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

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

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

but in case i'm using object

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

doesn't seem work

reason object same content not same objects e.g.

var = [{'id':1, 'value':10}, {'id':2, 'value':20}];  a.indexof({'id':1, 'value':10}) 

it not return 0 -1 because searching different object

see source code http://underscorejs.org/underscore.js, _.difference uses _.contains

_.difference = function(array) {   var rest = concat.apply(arrayproto, slice.call(arguments, 1));   return _.filter(array, function(value){ return !_.contains(rest, value); }); }; 

and _.contains uses indexof hence not find objects unless point same object.

you can improve underscore _.contains looping through items , calling compare callback, should able pass difference or contains function or can check this version improves contains methods


Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -