从嵌套数组中获取唯一元素的 JS 模式是什么?
What is the JS pattern to get unique elements from nested array?
我从 MongoDB.aggregate 得到以下结果:
[{
_id: ObjectId(1),
_author: ObjectId(2),
comments: [
{
_author: ObjectId(2),
text: '...'
},
{
_author: ObjectId(3),
text: '...1'
},
{
_author: ObjectId(3),
text: '...2'
}...
]
}...]
我需要从所有元素(包括嵌套)中获取所有唯一作者 _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);
}
我从 MongoDB.aggregate 得到以下结果:
[{
_id: ObjectId(1),
_author: ObjectId(2),
comments: [
{
_author: ObjectId(2),
text: '...'
},
{
_author: ObjectId(3),
text: '...1'
},
{
_author: ObjectId(3),
text: '...2'
}...
]
}...]
我需要从所有元素(包括嵌套)中获取所有唯一作者 _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);
}