OBJECTIVE: given two arrays, determine whether there are identical entries (that is, shared by both) or different entries (that is, unshared by both) and report such instances.
function compareArrays(array1, array2, mode){
if(typeof array1!='object' || typeof array2!='object' || typeof array1['length']=='undefined' || typeof array2['length']=='undefined'){/*bad input*/return false;};
return (!mode)?
array1.filter( function(i, arr){return array2.indexOf(i)>-1;} ).filter( function(i){return array2.filter( function(i){return array1.indexOf(i)>-1;} ).indexOf(i)>-1;} ):
[array1.filter( function(i, arr){return array2.indexOf(i)==-1;} ), array2.filter( function(i){return array1.indexOf(i)==-1;} )];
/*keep this comment to reuse freely
http://www.fullposter.com/?1*/}Remove colors
INPUTS: first two inputs must be two
numerically indexed arrays.
Last argument a number: if none or zero, the function returns the shared entries. If passed as number 1, the function returns the unshared entries.
RETURNS: boolean
false if the input arguments are not arrays.
Otherwise if the third parameter is not passed or is passed as zero, it returns an array carrying the shared values.
If the third parameter is passed as 1, it returns an array of two arrays, each of them again an array: the first array entry, placed at index 0, is an array that carries the values present in the first input array but not in the second input array; the second array entry, placed at index 1, is an array that carries the values present in the second input array but not in the first input array.
CAVEATS: uses the built in javascript method
filter, which is however not available on all platforms. Currently, all major browsers implement it, though.
It is unknown how the function may perform on very big arrays. Being javascript, your function should run on reasonably long arrays namely fit to be handled on the client side (whose memory and calculation power is unknown nearly by definition), whereas for big input data it is advisable to perform such checks on the server side, possibly; for this purpose you may see
PHP Array Compare Differences: Find In Arrays Items Identical, Added, Discarded or, also,
Php To Find Identical Items Present In All The Input Arrays: Intersect Arrays,
Php Search And Find Item In Arrays: Detect Presence In Any Or All Input Arrays
Example of use:
var a1=[1,2,3,4,5,9];
var a2=[2,5,6,7,8];
var different=compareArrays(a1, a2, 1);
var equals=compareArrays(a1, a2, 0)
alert('array1 was: '+a1+'\narray2 was: '+a2+'\n\nPresent in array1 but not in array2: '+different[0]+'\nPresent in array2 but not in array1: '+different[1]+'\nPresent in both: '+equals);Remove colors