In PHP exists a function array_diff (http://php.net/manual/de/function.array-diff.php) which returns the difference of two arrays. I have tried the implement my own version in JavaScript.
Any feedback is welcome. :)
function getArrayDiff(a, b) {
var ret = [],
merged = [];
merged = a.concat(b);
for (var i = 0; i < merged.length; i++) {
// When the element is contained ONLY
// one time then the search from
// left returns the same value as
// the search from the right.
if (merged.indexOf(merged[i]) ==
merged.lastIndexOf(merged[i])) {
// ... in that case the element
// is pushed to the result array.
ret.push(merged[i]);
}
}
return ret;
}
// -- Test ----------
a = [2, 4, 8, 16, 32];
b = [2, 4, 32, 64, 128, 256];
console.log(getArrayDiff(b, a));
Live Demo on CodePen: http://codepen.io/mizech/pen/GpVMEd