Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two arrays in Javascript - Returning differences

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.

like image 760
Hans Avatar asked Aug 08 '10 03:08

Hans


1 Answers

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

like image 80
Hans Avatar answered Oct 06 '22 01:10

Hans