Skip to content

Instantly share code, notes, and snippets.

@sepiariver
Last active December 21, 2017 12:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sepiariver/149de4a2aedd8f0adedf8caa12691868 to your computer and use it in GitHub Desktop.
Save sepiariver/149de4a2aedd8f0adedf8caa12691868 to your computer and use it in GitHub Desktop.
// 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;
};
}
@sepiariver
Copy link
Author

This could probably use improvement/optimization, but it's handy.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment