简体   繁体   中英

Average function with collection using Meteor.js

I need to calculate an average value with Meteor.js using multiple values inside a collection.

In particular, i need to do calculate two things:

  1. The difference between the last and the first obj.km
  2. The sum of all the obj.liters

Using javascript I would have written something like this:

 var arr = [{ 'km': 12000, 'liters': 20 }, { 'km': 12140, 'liters': 50 }, { 'km': 12240, 'liters': 45 }]; function calculate_avg() { var sum_liters = 0, arrlength = arr.length; for(i = 0; i < arrlength; i++) { sum_liters += arr[i].liters; } return ((arr[arrlength-1].km - arr[0].km)/sum_liters); }; 

In meteor I am defining a collection named "Refills":

 Refills = new Meteor.collection('refills'); // and I insert some example data like in the javascript array Refills.insert({ 'km': 12000, 'liters': 20 }); Refills.insert({ 'km': 12500, 'liters': 15 }); Refills.insert({ 'km': 13000, 'liters': 35 }); //etc. 

What is the best way to do that?

I tried to do something like this:

 Template.refills.helpers({ avg: function(){ var sum_liters = 0, diff_km = 0; Refills.find().map(function (doc, index, cursor) { //?? var diff_km = doc[last].km - doc[0].km var sum_liters += doc.liters; return ((/*diff_km*/)/sum_liters); }); } }); 

Thank you in advance to anybody who will help.

Give this a try:

Template.refills.helpers({
  avg: function() {
    // sort refills by km so the math in the last step makes sense
    var refills = Refills.find({}, {sort: {km: 1}}).fetch();
    // use a simple reduce to compute the sum
    var totalLiters = _.reduce(refills, (function(s, r) {return s + r.liters;}), 0);
    // return the average (total distance) / (total liters)
    return (_.last(refills).km - _.first(refills).km) / totalLiters;
  }
});

You need to use fetch on the cursor so you can manipulate an array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM