Sharepoint - How to group distinct values from a list using odata rest api

According to Use OData query operations in SharePoint REST requests, Grouping is not supported.

The solution, is to apply grouping for the JSON results returned from REST endpoint.

Example

Suppose the following function is used for getting list items via SharePoint REST API:

function getListItems(url, listname, query, complete, failure) {
    $.ajax({
        url: url + "/_api/web/lists/getbytitle('" + listname + "')/items" + query,
        method: "GET",
        headers: { "Accept": "application/json; odata=verbose" },
        success: function (data) {
            complete(data.d); 
        },
        error: function (data) {
            failure(data);
        }
    });
}

Then you could retrieve unique values from JSON array as demonstrated in answer Get unique results from JSON array using jQuery:

function groupBy(items,propertyName)
{
    var result = [];
    $.each(items, function(index, item) {
       if ($.inArray(item[propertyName], result)==-1) {
          result.push(item[propertyName]);
       }
    });
    return result;
}

The usage

getListItems('https://tenant.sharepoint.com/project','Tasks','?select=Title',
    function(items){    
       var taskNames = groupBy(items,'Title');
       console.log(taskNames);
    },
    function(error){
       console.log(JSON.stringify(error));
    }
);

I know it's a relatively old post but, for anyone who's still looking for an answer on this, querying for both grouping and aggregations(Totals) is supported in REST. Following are the two links for both the operations: -

  • SharePoint Grouping REST
  • SharePoint Aggregation REST

You can always pull the entire data and then apply your custom logic but there will be following issues: -

  • Applying custom grouping logic will make your application slower. If SharePoint is directly providing the grouped result then why do it yourself?
  • While aggregation functions like SUM,AVG,etc may be easy to implement (will still be slower) but, doing your custom calculation for Std Dev and Variance can be really complicated!

All in all, nothing can beat the performance of directly getting grouped result from SharePoint :)