You should look at each element of both arrays to get the difference between them. So there is no other way than iterating over both arrays:
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 sorting arrays and start with an inner loop with the element after the last match and break it if the value is greater:
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 arrays is also worth it.
Gumbo source share