在对象数组上使用下划线的“差异”方法 [英] 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];
和 _。差异(a,b)
回复 [1,3,4]
但是如果我正在使用像
var a = [{'id':1, 'value':10}, {'id':2, 'value':20}];
var b = [{'id':1, 'value':10}, {'id':4, 'value':40}];
似乎不起作用
推荐答案
原因很简单,具有相同内容的对象不是同一个对象,例如
Reason is simply that object with same content are not same objects e.g.
var a = [{'id':1, 'value':10}, {'id':2, 'value':20}];
a.indexOf({'id':1, 'value':10})
它不会返回0而是-1,因为我们正在搜索不同的对象
It will not return 0 but -1 because we are searching for a different object
参见源代码 http://underscorejs.org/underscore.js , _。差异
使用 _。包含
_.difference = function(array) {
var rest = concat.apply(ArrayProto, slice.call(arguments, 1));
return _.filter(array, function(value){ return !_.contains(rest, value); });
};
和 _。contains
最终使用 indexOf
因此除非它们指向同一个对象,否则不会找到对象。
and _.contains
ultimately uses indexOf
hence will not find objects unless they point to same object.
你可以改进下划线 _.contains
通过遍历所有项目并调用比较回调,您应该能够传递给差异或包含函数,或者您可以检查此版本改进包含方法
You can improve the underscore _.contains
by looping through all items and calling a compare callback, which you should be able to pass to difference or contains function or you can check this version which improves contains methods
这篇关于在对象数组上使用下划线的“差异”方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!