在Javascript两个数组比较 - 选举差异 [英] Comparing two arrays in Javascript - Returning differences
问题描述
假设我们有:
array1 = ['A', 'B', 'C', 'D', 'E']; array2 = ['C', 'E'];
有没有一个成熟和快速的解决方案,对对方两个数组比较,返回没有出现在两个数组(这里C和E)的值一个阵列。
所以:
Is there a proven and fast solution to compare two arrays against each other, returning one array without the values appearing in both arrays (C and E here). So:
array3 = ['A', 'B', 'D']
应溶液的输出。 (jQuery的可能参与)
should be the output of the solution. (jquery may be involved)
THX。
推荐答案
这是一组差异。一个简单的实现是:
This is a set difference. A simple implementation is:
jQuery.grep(array1, function(el)
{
return jQuery.inArray(el, array2) == -1;
});
这是O(M * n),其中这些都是数组的大小。您的可以的做到在O(M + N),但你需要使用某种类型的哈希集合的。您可以使用JavaScript对象作为一个简单的哈希字符串设定。对于相对小数组,上面应该是不错。
This is O(m * n), where those are the sizes of the arrays. You can do it in O(m + n), but you need to use some kind of hash set. You can use a JavaScript object as a simple hash set for strings. For relatively small arrays, the above should be fine.
这篇关于在Javascript两个数组比较 - 选举差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!