Created
May 15, 2013 15:29
-
-
Save detj/5584848 to your computer and use it in GitHub Desktop.
Finding duplicate objects within an array inside another array.
Requires underscore
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
!#/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