I am trying to find a fast method for comparing two arrays and returning the difference in elements of the arrays. I came up with something of N2, but with few more loops, is there a better way to do this?
/**
* Return the difference of two arrays
*
* @param {Array} other, the second array to be compared
* @param {Funciton} comparison_function, callback function for comparisons
* @returns {Array} 0 -- indexes of elements only in the first array
* 1 -- indexes of elements only in the second array
*/
Array.prototype.difference = function(other, comparison_function){
comparison_function = comparison_function || function(a,b){ return a == b;};
var extra = [],
matched = []
element_found = false;
// fill matched with all values
for(var _j = 0; _j < other.length; _j++){matched.push(_j);}
for(var _i = 0; _i < this.length; _i++){
element_found = false;
for(var _j = 0; _j < other.length; _j++){
if(comparison_function(this[_i], other[_j])){
matched[_j] = undefined;
element_found = true;
break;
}
}
if(!element_found) extra.push(_i);
}
return [extra, matched.filter(function(x){ return x !== undefined })];
}