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