Sum up "field num" in Types

2 posts, 0 answers
  1. Yi
    Yi avatar
    6 posts
    Member since:
    Jul 2013

    Posted 13 Jan 2014 Link to this post

    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?

  2. Anton Dobrev
    Anton Dobrev avatar
    607 posts

    Posted 15 Jan 2014 Link to this post

    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');
        then(function (data) {
              response.additionalData.TotalCount = sumArray(data.result);
            function (err) {

    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;
          responseResult = [responseResult];
         response.additionalData.TotalSum = sumArray(responseResult);

    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.

    Anton Dobrev

    Explore the entire Telerik portfolio by downloading Telerik DevCraft Ultimate.

Back to Top