To get elements from the array that are not present in another array.
var a = [2, 4, 8, 16, 32],
b = [2, 4, 32, 64, 128, 256];
// Define custom method on Array prototype
// Pass the array as parameter
Array.prototype.diff = function (arr) {
// Merge the arrays
var mergedArr = this.concat(arr);
// Get the elements which are unique in the array
// Return the diff array
return mergedArr.filter(function (e) {
// Check if the element is appearing only once
return mergedArr.indexOf(e) === mergedArr.lastIndexOf(e);
});
};
// How to call?
var diff = a.diff(b);
console.log(diff);
document.write('<pre>' + JSON.stringify(diff, 0, 4) + '</pre>');
[
8,
16,
64,
128,
256
]
Shorter version:
var diff = array1.concat(array2).filter(function (e, i, array) {
// Check if the element is appearing only once
return array.indexOf(e) === array.lastIndexOf(e);
});
Tags:
javascript