You have to look at each element of both array to get the difference of them. So there is no other way than iterating both array:
Array.prototype.diff = function(otherArray) {
var diff = [], found;
for (var i=0; i<this.length; i++) {
found = false;
for (var j=0; j<otherArray.length; j++) {
if (this[i] == otherArray[j]) {
found = true;
break;
}
}
if (!found) {
diff.push(this[i]);
}
}
return diff;
};
var a = [1,2,3,4],
b = [5,3,2,6];
var aDiffB = a.diff(b),
bDiffA = b.diff(a);
You can skip some comparisons when the arrays are sorted and start with the inner loop with the element after the last match and break it if the value is larger:
Array.prototype.diff = function(otherArray) {
var diff = [], found, startAt = 0,
a = this.sort(),
b = otherArray.sort();
for (var i=0; i<a.length; i++) {
found = false;
for (var j=startAt; j<b.length; j++) {
if (a[i] > b[j]) {
break;
}
if (a[i] == b[j]) {
found = true;
startAt = j + 1;
break;
}
}
if (!found) {
diff.push(a[i]);
}
}
return diff;
};
But sorting both array does also cost.