Skip to content

Instantly share code, notes, and snippets.

@detj
Created May 15, 2013 15:29
Show Gist options
  • Save detj/5584848 to your computer and use it in GitHub Desktop.
Save detj/5584848 to your computer and use it in GitHub Desktop.
Finding duplicate objects within an array inside another array. Requires underscore
!#/usr/bin/node
var _ = require('underscore');
var duplicates, uniques, temp;
var original = [
{"tags": [{_id: ObjectId(1), name: "tag1"}, {_id: ObjectId(2), name: "tag2"}, {_id: ObjectId(3), name: "tag3"}]},
{"tags": [{_id: ObjectId(2), name: "tag2"}, {_id: ObjectId(4), name: "tag4"}, {_id: ObjectId(3), name: "tag3"}]},
{"tags": [{_id: ObjectId(1), name: "tag1"}, {_id: ObjectId(3), name: "tag3"}, {_id: ObjectId(2), name: "tag2"}]}
];
uniques = [];
temp = [];
_.each(original, function(tagObj) {
var tags = tagObj.tags;
_.each(tags, function(tag) {
if (!_.contains(temp, toString(tag._id))) {
temp.push(toString(tag._id));
uniques.push(tag);
}
})
});
console.log(temp);
console.log(uniques);
function ObjectId(str) {
return {"$id": str};
}
function toString(obj) {
return obj["$id"];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment