0

extreme newbie here. I have a list with 15 items. There are five items with the title "One", five with the title "Two", and five with the title "Three". Each of the items have a corresponding number column. I need to loop through this list and end up with a view like this:

  • Name:"One" - Total (from number column):10 (or whatever number)
  • Name:"Two" - Total (from number column):7
  • Name:"Three" - Total (from number column):6

My code isn't working (probably for obvious reason but I'm just learning so can't see it). How would I accomplish this? Thanks!

$(document).ready(function(){   
    getCategories("MyList"); // start it off

});


function getCategories(listName){
    var url = _spPageContextInfo.siteServerRelativeUrl+
        "/_api/lists/getbytitle('MyList')/items?"+ 
        "$select=Rank,RequestName";
    $.ajax({
        url: url,
        method: 'GET',
        beforeSend: function (XMLHttpRequest){
            XMLHttpRequest.setRequestHeader('Accept', 'application/json; odata=verbose');
            },
        success: function( data ) {     
                createHTML(data, listName)
        }   
    }); 
}

function createHTML(data, listName){
var arr = data.d.results;

var container = $('#rankIt');

        var categoryLinksContainer = $('<div class="links-list" />');
var added = 0;          
var itemName = "";
 for(var i in arr){
        var item = arr[i];  
        var rank = item.Rank 
        var title = item.RequestName;

     itemName = title;
     added = rank;
      if(itemName == title){
          added = added + parseInt(rank);

      }

        var item = arr[i];  
        var rank = item.Rank 
        var title = item.RequestName;
        categoryLinksContainer.append(
                '<div class="link"><a href="#">'+itemName+'</a></div><div>'+added+'</div>'
        );
                categoryLinksContainer.appendTo(container);
  } 
}
1

You can try below code. This should work.

<script type="text/javascript">
    $(document).ready(function () {
    var summary ={};
        getListData().then(
            function (data, status, jqXHR) {
                var items = data.d.results;
                summary = groupBy(items);
                $.each(summary, function(index, val) {
                alert("Name:" + index + "- Total " + val);
                });                    
            },
            function (jqXHR, status, error) {
                var err = eval("(" + jqXHR.responseText + ")");
                console.log(err.Message);
            });
    });

    function getListData() {
        var listName = "Test"; //List Name
        var getbaseUrl = SP.Utilities.UrlBuilder.urlCombine(_spPageContextInfo.siteAbsoluteUrl, "_api/web/lists/");
        getbaseUrl += "GetByTitle('" + listName + "')/items?$select=Title,Number&$orderby=ID asc";
        var dfd = $.Deferred();

        dfd = $.ajax({
            url: encodeURI(getbaseUrl),
            type: "GET",
            contentType: "application/json; odata=verbose",
            headers: {
                "accept": "application/json; odata=verbose"
            }
        });
        return dfd.promise();
    }

    function groupBy(items){
        var result= {};
        var sum;
        console.log(items);                    
        $.each(items, function(index, item) {
        sum = result[item.Title] || 0;
        result[item.Title] = sum + item.Number;                     
});
return result;
}
</script> 

This should print

Name:One- Total 10

Name:Two- Total 7

Name:Three- Total 6

  • Thanks! this is working but it is returning 'Total 062' instead of '8', for example. looks like it just putting the values together as a string. any idea as to why? – loady toad Sep 14 '17 at 20:19
  • 1
    Looks like data type is string for the 'Number' column in your instance. Try doing parseInt(item.Number) in the groupby function. This will convert string to integer. – Pradeep Kothamale Sep 14 '17 at 20:33
  • worked. thanks again! i really appreciate the guidance! – loady toad Sep 14 '17 at 20:34
  • quick question. I've tried for hours to figure this out. your original script is working to return the sum of all items with same title. but i need alter this to return the sum of all items with the same title divided by the number of item there are with that title. in other words, some of the item numbers are zero and i don't want to factor those items into the total. is there an easy way to do this? i am stumped and really appreciate your guidance/knowledge! thanks! @PradeepKothamale – loady toad Oct 3 '17 at 23:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.