Skip to content

Instantly share code, notes, and snippets.

@or9
Last active January 18, 2016 05:13
Show Gist options
  • Save or9/ad6382f37be03da7fc84 to your computer and use it in GitHub Desktop.
Save or9/ad6382f37be03da7fc84 to your computer and use it in GitHub Desktop.
Extract an array of differences by key from two arrays of objects
Array.prototype.extractDiff = extractDiff;
var arr1 = [{ hash: 1234 }, { hash: "abcdefghijk" }];
var arr2 = [{ hash: 1234 }, { hash: "abcdefghijklmnopqrstuvwxyz" }];
var arr3 = [{ hash: 1234 }, { hash: "abcdefghijklmnopqrstuvwxy" }, { hash: "xyz1234" }];
var arr4 = [{ hash: "abcdefghijklmnopqrstuvwxy" }, { hash: "xyz1234" }, { hash: 1234 }];
var diff1 = arr1.extractDiff(arr2, "hash");
var diff2 = arr3.extractDiff(arr1, "hash");
var diff3 = arr4.extractDiff(arr3, "hash"); // returns [] because 3 and 4 are just different arrangements of same objects
/**
* @description Find difference between two Arrays of Objects
* @param Comparison {Object[]} - Array of objects in which to find differences
* @param Key {String} - Key to perform match against in array's objects
* @returns Differences {Array}
*/
function extractDiff (comparisonArr, key) {
if (!key) {
return new Error("Requires a key for comparison");
}
var longer, shorter;
if (this.length < comparisonArr.length) {
longer = comparisonArr;
shorter = this;
} else {
longer = this;
shorter = comparisonArr;
}
return longer.map(findMatchesInArray, longer)
.filter(trimUndefined);
function findMatchesInArray (currentValue) {
var matches = shorter.filter(function (comparison) {
return comparison[key] === currentValue[key];
});
if (!matches.length) {
return currentValue;
}
}
function trimUndefined (val) {
return val !== undefined;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment