在 JavaScript 中,如何求出两个数组的交集和差集?

两个任意元素的数组,比较出两个数组中相同的元素和不同的元素。
关注者
230
被浏览
163,314

13 个回答

Underscore.js


intersection

_.intersection(*arrays)
Computes the list of values that are the intersection of all the arrays . Each value in the result is present in each of the arrays .

_.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]);
=> [1, 2]

difference

_.difference(array, *others)
Similar to without , but returns the values from array that are not present in the other arrays.

_.difference([1, 2, 3, 4, 5], [5, 2, 10]);
=> [1, 3, 4]

但是这个只能用于原生类型,如果想要用于对象数组的话,丢个链接在这里

stackoverflow.com/quest

用 CoffeeScript 啦

a ∩ b:

intersection = (e for e in a when e in b)

a - b:

diff = (e for e in a when !(e in b))

其中 e in b 用了 indexOf, 所以会有 NaN 不属于 [NaN] 的问题...

NaN 是 Javascript 的设计缺陷之一. 你说两个看起来一样的东西应该相等吧, 但 NaN 可以是正无穷大可以是负无穷大, 从定义上就是几乎不能相等的... 不过正确编写的代码是不会出现 NaN 的