比较 Javascript 中的两个数组 - 返回差异

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3432929/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 01:09:32  来源:igfitidea点击:

Comparing two arrays in Javascript - Returning differences

javascriptarrayscomparison

提问by Hans

Assuming we have:

假设我们有:

array1 = ['A', 'B', 'C', 'D', 'E']; array2 = ['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:

是否有一种行之有效的快速解决方案来比较两个数组,返回一个数组而没有出现在两个数组中的值(此处为 C 和 E)。所以:

array3 = ['A', 'B', 'D']

should be the output of the solution. (jquery may be involved)

应该是解决方案的输出。(jquery可能涉及)

thx.

谢谢。

回答by Hans

I accepted Matthews Solution, but dont want to ignore a different faster solution i just found.

我接受了 Matthews 解决方案,但不想忽略我刚刚找到的另一个更快的解决方案。

 var list1 = [1, 2, 3, 4, 5, 6];
 var list2 = ['a', 'b', 'c', 3, 'd', 'e'];
 var lookup = {};

 for (var j in list2) {
      lookup[list2[j]] = list2[j];
  }

  for (var i in list1) {
      if (typeof lookup[list1[i]] != 'undefined') {
          alert('found ' + list1[i] + ' in both lists');
          break;
 } 
 }

Source: Optimize Loops to Compare Two Arrays

来源:优化循环以比较两个数组

回答by Matthew Flaschen

This is a set difference. A simple implementation is:

这是一个集合差异。一个简单的实现是:

jQuery.grep(array1, function(el)
                    {
                        return jQuery.inArray(el, array2) == -1;
                    });

This is O(m * n), where those are the sizes of the arrays. You cando 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.

这是 O(m * n),其中这些是数组的大小。您可以在 O(m + n) 中完成,但您需要使用某种散列集。您可以将 JavaScript 对象用作字符串的简单哈希集。对于相对较小的数组,以上应该没问题。

回答by akonsu

a proven fast solution that i know of is a binary search that you can use after you sort one of the arrays. so the solution takes time that depends on the sorting algorithm. but is at least log(N).

我所知道的一个经过验证的快速解决方案是二分搜索,您可以在对其中一个数组进行排序后使用它。所以解决方案需要时间,这取决于排序算法。但至少是 log(N)。