Skip to content

Instantly share code, notes, and snippets.

@dandybreath
Created July 1, 2015 15:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dandybreath/85aa931c979f20d639f0 to your computer and use it in GitHub Desktop.
Save dandybreath/85aa931c979f20d639f0 to your computer and use it in GitHub Desktop.
javascript union array of objects
function checkIdentical(o1, o2, properties){
var identical = false;
for (var k = 0; k < properties.length; k++) {
var cp = properties[k];
if (o1[cp] == o2[cp]) {
identical = true;
}
else {
identical = false;
break;
}
}
return identical
}
function unyon(arr1, arr2, properties) {
var res = arr1.concat(arr2);
for (var i = 0; i < res.length; i++) {
for (var j = i + 1; j < res.length; j++) {
var identical = checkIdentical(res[i], res[j], properties);
if (identical) {
res.splice(i, 1);
j -= 1; // add this
}
}
}
return res;
}
var s1 = [{ x: 1, y: 2 }, { x: 2, y: 2 }];
var s2 = [{ x: 2, y: 1 }, { x: 2, y: 2 }];
var test1 = unyon(s1, s2, ['x', 'y']);
var test2 = unyon(s1, s2, ['x']);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment