Summaries of data


#1

Hi all,

I’m looking for an elegant way to summarize some data that is split into categories.

I’ve made a codepen : http://codepen.io/anon/pen/gbPpLy

I would like to present the data in the format described in the “Aiming for” section of the page. As you can see it’s split up by “type” with the total of said type displayed below.

I know it’s possible to specifically filter an array of objects with a variable (e.g. filter type by “Type 1” and then make another filter by “Type 2”), but let’s assume that we do not know the different types until we get the data.

Hopefully that makes sense and someone can help.

As always, thank you very much
-Chris


#2

The most elegant solution I’ve found so far is as follows.

It uses two additional JS functions an an additional $scope function (which I wanted to ignore if possible) but it does what is required.

HTML

<div class="row">
          <div class="col-50 header">
            Item
          </div>
          <div class="col-25 header">
            Type
          </div>
          <div class="col-25 header">
            Val
          </div>
        </div>
        <div ng-repeat-start="atype in returnTypes()" class="row">
          <div class="col subheader">
            {{atype}}
          </div>
        </div>
        <div class="row" ng-repeat="item in filtered = (data | filter:{type:atype})">
          <div class="col-50 rowitem">
            {{item.name}}
          </div>
          <div class="col-25 rowitem">
            {{item.type}}
          </div>
          <div class="col-25 rowitem">
            {{item.value}}
          </div>
        </div>
        <div ng-repeat-end class="row">
          <div class="col-50 header">
            
          </div>
          <div class="col-25 header">
            Total
          </div>
          <div class="col-25 header">
            {{filtered.sum('value')}}
          </div>
        </div>

JS

function uniqueFromObjectArray(arr, key){
  console.log(unique);
  var unique = [];
  for(var i = 0; i < arr.length; i++){
    if(unique.indexOf(arr[i][key]) == -1){
      unique.push(arr[i][key]);
    }
  }
  console.log(unique);
  return unique;
}

Array.prototype.sum = function (prop) {
    var total = 0
    for ( var i = 0, _len = this.length; i < _len; i++ ) {
        total += this[i][prop]
    }
    return total
}

Scope

$scope.returnTypes = function(){
    return uniqueFromObjectArray($scope.data,'type');
  }