Search code examples
javascriptarraysmongodbmongooseunique

What is the JS pattern to get unique elements from nested array?


I have the following result from MongoDB.aggregate:

[{
   _id: ObjectId(1), 
   _author: ObjectId(2),
   comments: [
      {
         _author: ObjectId(2),
         text: '...'
      },
      {
         _author: ObjectId(3),
         text: '...1'
      },
      {
         _author: ObjectId(3),
         text: '...2'
      }...
   ]
}...]

I need to get all unique authors _author field from all elemnts (including nested):

var uniqAuthors = magicFunction(result) // [ObjectId(2), ObjectId(3)] ;

What is the best and compact way to make it with pure JS?


Solution

  • Array.prototype.reduce can help you:

    var unique = result[0].comments.reduce(function(uniqueAuthors, comment) {
      if (uniqueAuthors.indexOf(comment._author) === -1) {
         uniqueAuthors.push(comment._author);
      }
      return uniqueAuthors;
    }, []);
    //Verify the author from document
    if (unique.indexOf(result[0]._author) === -1) {
       uniqueAuthors.push(result[0]._author);
    }