-1

How can i compare this two arrays and create a new array (filtered) based on if any number in Array1 exist in Array2. Both arrays is dynamic and can have different lengths.

Array1 = 3796, 3831, 3858, 3860

Array2 = 3796, 4566, 2932, 3831, 3290, 3858, 4599, 3293 etc etc..

In this case i want my output to be:

Array3 = 4566, 2932, 3290, 4599, 3293
Peter
  • 45
  • 1
  • 2
  • 6
  • can you tell us the relevance between the two arrays, or should we try to figure it out? – epoch Feb 20 '15 at 12:12
  • Why not just use Array.prototype.filter? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FArray%2Ffilter – NMunro Feb 20 '15 at 12:21

3 Answers3

0

I assume you are comparing normal array. If no, you need to change for loop to for .. in loop.

function arr_diff(a1, a2)
{
  var a=[], diff=[];
  for(var i=0;i<a1.length;i++)
    a[a1[i]]=true;
  for(var i=0;i<a2.length;i++)
    if(a[a2[i]]) delete a[a2[i]];
    else a[a2[i]]=true;
  for(var k in a)
    diff.push(k);
  return diff;
}

The function will return array having difference of the two arrays

void
  • 36,090
  • 8
  • 62
  • 107
  • Never iterate through array with `for .. in` loop, keep it only for object properties iteration. Array should be iterated with traditional `for` loop only. – VisioN Feb 20 '15 at 12:33
  • Yes @VisioN, That is what i said. If it is not a usual array then use for...in. – void Feb 20 '15 at 12:37
0

You can try this:

function in_array(needle, haystack){
   for (var i = 0; i < haystack.length; i++){
      if (needle == haystack[i]) return true;
   }
   return false;
}    

for (var i = 0; i < array1.length; i++){
       if (!in_array(array1[i], array2){
          var index = array1.indexOf(array1[i]);
          array1.splice(index, 1);
       }
}

I have not tested it, but i guess it should work.

maxeh
  • 1,373
  • 1
  • 15
  • 24
0

This may be the shortest solution:

function diff(a, b) {
    var c = [].slice.call(a.length > b.length ? a : b);  // clone the longest array
    return c.filter(function(c) { return a.indexOf(c) < 0 });  // filter out intersects
}

var a = [3796, 3831, 3858, 3860],
    b = [3796, 4566, 2932, 3831, 3290, 3858, 4599, 3293];

console.log( diff(a, b) );  // [4566, 2932, 3290, 4599, 3293]
VisioN
  • 143,310
  • 32
  • 282
  • 281