JSFiddle - React, Tailwind, and code Playground
JavaScript
console.clear();
// in my case b will ALWAYS be a subset of a, but may lack elements that exist in a
// please correct me if I used `subset` incorrectly
// NOTE: I altered the data in both to see how my function would handle values that are in b but not in a
// as expected it simply ignores them
var myA = [{id: 210}, {id: 2}, {id: 3}, {id: 467}, {id: 5}, {id: 798}],
myB = [{id: 1}, {id: 2}, {id: 3}, {id: 5}, {id: 6}];
function getArrayDifference(a, b) {
var result = [],
aLength = a.length,
bLength = b.length;
for (var i = 0; i < aLength; i++) {
var inB = checkInB(a[i]);
console.log("inB: " , inB, "a[i]: ", a[i]);
if (! inB) { result.push(a[i]) };
}
function checkInB(obj) {
for (var i = 0 ; i < bLength; i++) {
if (obj.id === b[i].id) {
console.log("obj ", obj.id, "b", b[i].id);
return true;
}
}
return false;
}
return result;
}
// I want result to contain only [{id:4}, {id:21}, {id:7}] - the elements in a but not in b
var resA = getArrayDifference(myA, myB);
console.log("final result array for A", resA);
// will contain [{id: 1, {id: 6}]
var resB = getArrayDifference(myB, myA)
console.log("final result array for B", resB);
// If I want a true difference I would have to combine the results
var difference = resB.concat(resA);
console.log("Full Difference: ", difference);