简体   繁体   English

使用Meteor.js进行收集的平均功能

[英]Average function with collection using Meteor.js

I need to calculate an average value with Meteor.js using multiple values inside a collection. 我需要使用Meteor.js使用集合内的多个值来计算平均值。

In particular, i need to do calculate two things: 特别是,我需要计算两件事:

  1. The difference between the last and the first obj.km 最后一个和第一个obj.km之间的区别
  2. The sum of all the obj.liters 所有obj.liters的总和

Using javascript I would have written something like this: 使用javascript,我可能会这样写:

 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. 您需要在游标上使用访存 ,以便可以操纵数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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