Common elements in two arrays javascript

arrNum1 = new Array(1,2,3);
arrNum2 = new Array(2,3,4,5);
arrNum3 = new Array();

arrNum3 =  intersect_safe(arrNum1, arrNum2);

for(i=0;i<arrNum3.length;i++)
 alert(arrNum3[i]);

function intersect_safe(a, b)
{
  var ai=0, bi=0;
  var result = new Array();

   while(ai<a.length && bi < b.length )
  {
     if(a[ai] != b[bi])
     { 
       bi++; 
     }
     else
     {
       result.push(a[ai]);
       ai++;
       bi++;
     }
  }

  return result;
}

Leave a reply