我正在学习Meteor / Javascript并且有一个我似乎无法弄清楚的问题。这更像是一个2部分的问题。
我可以做我正在尝试使用Meteor Mongo并避免在Javascript中进行映射/缩减吗?
如何在Javascript中对下面提到的2D数组进行映射/缩小? (将是一个很好的学习例子)。
所以这是设置,我有一个Mongo集合,它有以下数据;
{
"_id" : "oBPoZCLo9JFhZGdtL",
"guest" : "Jin",
"itemLikes" : 25,
}
{
"guest" : "Jin",
"itemLikes" : 32,
"_id" : "xz7AgJv52e8QF6XuA"
}
{
"guest" : "Jin",
"itemLikes" : 20,
"_id" : "XHkJoJEDyxX8w9Zmc"
}
{
"guest" : "Jin",
"itemLikes" : 39,
"_id" : "LeN5Nqhgdn79MCbct"
}
{
"guest" : "Jim",
"itemLikes" : 17,
"_id" : "iuhM6v4yySrEpgeaY"
}
{
"guest" : "Lex",
"itemLikes" : 20,
"_id" : "ed6dmDMzXKJRaBxFM"
}
{
"guest" : "Lex",
"itemLikes" : 35,
"_id" : "dTiY7nEx9yNXQTp49"
}
{
"guest" : "Mel",
"itemLikes" : 21,
"_id" : "XRb7Yz84nEDJhpSQh"
}
{
"guest" : "Mel",
"itemLikes" : 17,
"_id" : "KX9TSsWrJREQtaSNu"
}
{
"guest" : "Nance",
"itemLikes" : 39,
"_id" : "rJRr2WdBaWXEurbWf"
}
这是我用来解析数据的Meteor方法调用;
myFunctionName: function () {
var guestLikesTotal = []
_.reduce(_.map(MyCollection.find().fetch(), function(doc) {
//map
return [doc.guest, doc.itemLikes];
//the map gives me ["Jin", 25] for example
}),
function(memo, num){
//reduce
if (guestLikesTotal.length == 0) {
guestLikesTotal.push(num);
} else {
var count = guestLikesTotal.length;
for(var i=0;i<count;i++) {
if(guestLikesTotal[i][0] == num[0]) {
guestLikesTotal[i][1] += num[1];
} else {
// not sure what to put here
}
}
// this is wrong because its pushing items with the same "name" into the array
guestLikesTotal.push(num);
};
return memo+=1;
}, 0);
return guestLikesTotal;
}
我试图让guestLikesTotal看起来像这样;
[["Jin",116],["Jim",17],["Lex",55],["Nance",56]]
非常感谢对这2个问题的任何帮助。
答案 0 :(得分:0)
在javascript中,如果您的集合在数组中,则可以执行此操作:
var arr2 = [];
data.reduce( function (a, current, index) {
if (!arr2.hasOwnProperty(current.guest)) {
arr2[current.guest] = 0;
}
arr2[current.guest] += current.itemLikes;
}, data[0]);
var desired_arr = [];
for(var i in arr2) {
desired_arr.push([i, arr2[i]]);
}
console.log(desired_arr);