有没有办法在JavaScript中返回两个数组之间的差值?
例如:
var a1 = ['a', 'b'];
var a2 = ['a', 'b', 'c', 'd'];
// need ["c", "d"]发布于 2013-03-13 20:57:05
这是到目前为止获得您想要的结果的最简单的方法,使用jQuery:
var diff = $(old_array).not(new_array).get();diff现在包含了old_array中不包含在new_array中的内容
发布于 2012-07-06 06:44:52
The difference method in Underscore (或者它的替代产品,Lo-Dash)也可以做到这一点:
(R)eturns the values from array that are not present in the other arrays
_.difference([1, 2, 3, 4, 5], [5, 2, 10]);
=> [1, 3, 4]与任何下划线函数一样,您也可以在更面向对象的样式中使用它:
_([1, 2, 3, 4, 5]).difference([5, 2, 10]);发布于 2009-07-27 10:43:56
在这种情况下,您可以使用Set。它针对这种操作(并集、交集、差分)进行了优化。
确保它适用于您的案例,一旦它不允许重复。
var a = new JS.Set([1,2,3,4,5,6,7,8,9]);
var b = new JS.Set([2,4,6,8]);
a.difference(b)
// -> Set{1,3,5,7,9}https://stackoverflow.com/questions/1187518
复制相似问题