difference between two array

by slawe

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 = ['first_name', 'random_5', 'last_name', 'file_id', 'date', 'vin', 'model', 'year'],
		myB = ['first_name', 'file_id', 'random_1', 'date', 'last_name', 'random_2', 'vin', 'model', 'year', 'random_3', 'random_4'];

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 === b[i]) {
                console.log("obj ", obj, "b", b[i]);
                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);