"Csaba Gabor" <Cs***@z6.com > wrote in message
news:11******** **************@ g14g2000cwa.goo glegroups.com.. .
ef*****@epitome .com.sg wrote: How can I extract differences between two arrays using Javascript?
I hv for example, apple, orange, pear and another array with apple,
orange and I would like to get pear.
Here's one way, with an example:
function aDiff(aRay1, aRay2) {
// initialize aResult, and seed obj, removing dups
var obj = {}, aResult = [];
for (var idx in aRay1) obj[aRay1[idx]] = 1;
// now remove elements common to both
for (idx in aRay2) if (obj[aRay2[idx]]) delete (obj[aRay2[idx]]);
// assemble the result
for (idx in obj) aResult[aResult.length] = idx;
return aResult;
}
var a1 = ['cat', 'mouse', 'dog', 'elephant'];
var a2 = ['bush', 'dog', 'fire hydrant', 'cat'];
alert (aDiff(a1, a2).join(", "));
Csaba Gabor from Vienna
I'm not sure what the original poster's requirements are, but your
solution fails to identify 'fire hydrant' as being different. It seems
like that is what the OP is asking for, but I wonder if he's thought
about it. And if he does want all the differences between two arrays,
how does he want to represent those differences? One huge list? Two
lists showing the elements of array 1 not in array 2 and one showing
elements in array 2 not in array 1?
function aDiff2(arr1, arr2)
{
arr1 = arr1.concat();
arr1.sort();
arr2 = arr2.concat();
arr2.sort();
var arr1Idx = 0;
var arr2Idx = 0;
while (arr1Idx < arr1.length)
{
if (arr2[arr2Idx])
{
if (arr1[arr1Idx] == arr2[arr2Idx])
{
arr1.splice(arr 1Idx, 1);
arr2.splice(arr 2Idx, 1);
}
else
{
++arr2Idx;
}
}
else
{
++arr1Idx;
}
}
return { diff1:arr1, diff2:arr2 };
}
var a1 = ['cat', 'mouse', 'dog', 'elephant'];
var a2 = ['bush', 'dog', 'fire hydrant', 'cat'];
alert(aDiff2(a1 , a2).diff1.join( ));
alert(aDiff2(a1 , a2).diff2.join( ));
My version breaks down if the array(s) contain(s) duplicate items. I
didn't have to write a general purpose function to deal with this. It
also obviously fails if one array contains "Dog" and the other contains
"dog" (although that could be solved by sorting and comparing without
regard for case).
--
Grant Wagner <gw*****@agrico reunited.com>
comp.lang.javas cript FAQ -
http://jibbering.com/faq