I am learning Meteor/Javascript and have a issue I cant seem to figure out. This is more of a 2 part question.
Can I do what I am trying to do with Meteor Mongo and avoid mapping/reducing in Javascript?
How can I do a map/reduce of the 2D array mentioned below in Javascript? (would be a good learning example).
So here is the setup, I have a Mongo collection that has the following data;
{
"_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"
}
Here is the Meteor method call I am using to parse the data;
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;
}
I am trying to get guestLikesTotal to look like this;
[["Jin",116],["Jim",17],["Lex",55],["Nance",56]]
Any help with the 2 questions would be greatly appreciated.