最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Comparing two arrays in Javascript - Returning differences - Stack Overflow

programmeradmin2浏览0评论

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:

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

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

thx.

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:

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

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

thx.

Share Improve this question edited Aug 8, 2010 at 3:47 Björn asked Aug 8, 2010 at 3:13 BjörnBjörn 13.2k12 gold badges55 silver badges70 bronze badges 1
  • Are the arrays both always sorted, as in your example? If so, this can be done in linear time by just walking the arrays. – Ben Zotto Commented Aug 8, 2010 at 3:25
Add a comment  | 

3 Answers 3

Reset to default 13

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

 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

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 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.

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).

发布评论

评论列表(0)

  1. 暂无评论