This is a migrated thread and some comments may be shown as answers.

Sum up "field num" in Types

1 Answer 43 Views
Cloud Code
This is a migrated thread and some comments may be shown as answers.
This question is locked. New answers and comments are not allowed.
Yi
Top achievements
Rank 2
Yi asked on 13 Jan 2014, 11:28 PM
In my project, the Type "Activities" has a field, which is "num". How to sum up these numbers of all items ? 
Is there a way to fetch the items in Type one by one in the cloud code?

For example, how to sum up the numbers from 41 to 37 in the attached?

1 Answer, 1 is accepted

Sort by
0
Anton Dobrev
Telerik team
answered on 15 Jan 2014, 05:35 PM
Hi Yi,

Thank you for your question.

We have prepared two examples:
  •   the first returns the sum of all the items in the content type
  •   the second returns the sum of all items for the current response

Both approaches are using a helper function that iterates over the items and returns the sum of the fields. It looks like this:
function sumArray(arr){
  var len = arr.length;
  var i;
  var sum = 0;
  var radix = 10;
  for(i = 0; i < len; i++){
    sum += parseInt(arr[i].Num, radix);
  }
   
  return sum;
}

1. If you want to explicitly sum all the items in the content type and return their sum, please add the following code in the appropriate event in the cloud code:

var data = Everlive.Sdk.$.data('Activities');
    data.get().
    then(function (data) {
          response.additionalData.TotalCount = sumArray(data.result);
            done();
        },
        function (err) {
            done();
 });


2. The next example sums up only the items returned for the current response(for example you can have a filter applied before retrieving the items, or retrieving all items).
Everlive.Events.afterRead(function(request, response, context, done) {
  var responseResult = response.result;
  if(responseResult){
    if(!Array.isArray(responseResult)){
      responseResult = [responseResult];
    }
     response.additionalData.TotalSum = sumArray(responseResult);
  }
    done();
});

Please, let us know if these examples are helpful for you. If you need more details or an implementation of a more specific scenario, do not hesitate to contact us.

Regards,
Anton Dobrev
Telerik

Explore the entire Telerik portfolio by downloading Telerik DevCraft Ultimate.

Tags
Cloud Code
Asked by
Yi
Top achievements
Rank 2
Answers by
Anton Dobrev
Telerik team
Share this question
or