diff between two arrays code example
Example 1: diff two arrays javascript
function diffArray(arr1, arr2) {
return arr1
.concat(arr2)
.filter(item => !arr1.includes(item) || !arr2.includes(item));
}
Example 2: javascript get array difference
function arrayDiff (a1, a2) {
var a = [], diff = [];
for (var i = 0; i < a1.length; i++) {
a[a1[i]] = true;
}
for (var i = 0; i < a2.length; i++) {
if (a[a2[i]]) {
delete a[a2[i]];
} else {
a[a2[i]] = true;
}
}
for (var k in a) {
diff.push(k);
}
return diff;
}
console.log(arrayDiff(['red', 'white','green'], [ 'red','white', 'blue']));
Example 3: Diff Two Arrays
const diffArray = (arr1, arr2) => {
const diffArray = []
const uniqueArr = [...new Set([...arr1, ...arr2])];
uniqueArr.forEach(elem => {
if(!arr1.includes(elem) || !arr2.includes(elem))
diffArray.push(elem)
})
return diffArray
}
diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);