yj-t
5/17/2016 - 8:02 PM

Array.diff.js

// Array.diff()
if (typeof Array.prototype.diff === 'undefined') {
    
    Array.prototype.diff = function() {
        
        var result = arguments[0];
        delete arguments[0];
        
        if (!(result instanceof Array)) {
            throw new TypeError('1st argument passed to Array.diff was not an array');
        }
        
        // private utility function
        // from: http://adripofjavascript.com/blog/drips/object-equality-in-javascript.html
        var isEquivalent = function(a, b) {
            
            if (a === null || typeof a === 'undefined' || b === null || typeof b === 'undefined') return false;
            // Create arrays of property names
            var aProps = Object.keys(a);
            var bProps = Object.keys(b);
        
            // If number of properties is different,
            // objects are not equivalent
            if (aProps.length != bProps.length) {
                return false;
            }
        
            for (var i = 0; i < aProps.length; i++) {
                var propName = aProps[i];
        
                // If values of same property are not equal,
                // objects are not equivalent
                if (a[propName] !== b[propName]) {
                    return false;
                }
            }
        
            // If we made it this far, objects
            // are considered equivalent
            return true;
        };
        
        var arrays = arguments,
            c = arrays.length;
        // For each element in arguments array
        for (var i=0;i<c;i++) {
            var currentArray = arrays[i];
            if (!(currentArray instanceof Array)) continue;

            var ac = currentArray.length;
            for (var ai=0;ai<ac;ai++) {
                
                // redefine result.length var each iteration as it may have changed
                var rc = result.length;
                for (var ri=0;ri<rc;ri++) {
                    
                    var found = 0;
                    // test each element in result against currentArray element
                    if (typeof currentArray[ai] === 'object') {
                        if (isEquivalent(result[ri], currentArray[ai])) found++;
                    } else {
                        if (result[ri] === currentArray[ai]) found++;
                    }  
                    if (found > 0) delete result[ri];
                }
                              
            }            
        }
        
        // Return result
        var resultc = result.length,
            returnArray = [];
        for (var resulti=0;resulti<resultc;resulti++) {
            if (typeof result[resulti] !== 'undefined') returnArray.push(result[resulti]);
        }
        return returnArray;
        
    };
    
}