Calculating average over a collection

Hi Everyone,

I currently have a collection node full of models that I want to iterate over to calculate the average of a specific property in all the models. What’s the best way to approach this in Noodl?

We think For Each nodes may be the way to go, but it has potential to get messy fast. Is there another way to go about doing this?

Thanks in advance!

Hi,

The best way to do that is with a javascript node. You can check out the Model and Collection API here:

http://docs.getnoodl.com/noodl.collection.html

http://docs.getnoodl.com/noodl.model.html

So maybe something like (with reservation for typos):

var avg = 0;
var col = Noodl.Collection.get("the-id-of-my-collection");
col.each(function(model) {
avg += model.get("the-property-name");
})
avg /= col.size();

Then you can pass the avg value as the output of the javascript node. You can learn more about Javascript nodes here:

http://docs.getnoodl.com/javascript.html