Search code examples
javascriptangularjsgroupingmeanjs

How to group and calculate the total sum of items in subdocuments using AngularJS


I am using MEAN stack in my application with AngularJS as my front-end. I am trying to get total sum of my subdocuments but I did not get the desired result. my fiddle

The result I got

Summary:
1000
100
50
100
100
Total:undefined

The result I'm expecting

Summary:
1000
100
50
100
100
Total:1350

HTML

<ul>
    <li ng-repeat="mani in items">
      <p ng-repeat ="rohit in mani.colorshades ">
      {{rohit.order_quantity}}
      </p>
    </li>
    <p class="length">Total:{{items.length}}</p>
</ul>

Controller

$scope.items = [{
"_id": "56f91708b7d0d40b0036bc09",
"colorshades": [
    {
    "_id": "56f9177fb7d0d40b0036bc0c",
    "order_quantity": "1000",
    },
    {
    "_id": "56f9177fb7d0d40b0036bc0b",
    "order_quantity": "100",
    },
    {
    "_id": "56f919d7b7d0d40b0036bc13",
    "order_quantity": "50",
    }]
},
{
"_id": "56f367e6a7d3730b008d296a",
"colorshades": [
    {
      "_id": "56f3680ba7d3730b008d296c",
      "order_quantity": "100",
    }
]
},
{
"_id": "56e7af485b15b20b00cad881",
"colorshades": [
    {
    "_id": "56e7af7b5b15b20b00cad882",
    "order_quantity": "100",
    }
]
}];

$scope.getTotals = function () {
    var total = 0;
    for (var i = 0; i < $scope.item.colorshades.length; i++) {
        var item = $scope.item.colorshades[i];
        total += (item.order_quantity);
    }
    return total;
};

my fiddle


Solution

  • You have a two level loops, the code should be like that (don't forget to cast the strings by parseInt otherwise you will have a concatenation) :

    $scope.getTotals = function () {
    var total = 0;
    for (var i = 0; i < $scope.items.length; i++) {
    
        for (var j = 0; j < $scope.items[i].colorshades.length; j++) {
          total += parseInt(($scope.items[i].colorshades[j].order_quantity));
        }
    }
    return total;
    };