从嵌套数组中获取唯一元素的 JS 模式是什么

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

本文关键字:JS 模式 是什么 元素 唯一 嵌套 数组 获取      更新时间:2023-09-26

>我从MongoDB.aggregate得到以下结果:

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

我需要从所有 elemnts(包括嵌套)_author字段中获取所有唯一作者:

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

使用纯 JS 制作它的最佳和紧凑方法是什么?

Array.prototype.reduce可以帮助您:

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);
}