Lee Lee
Lee Lee

Reputation: 583

Get the sum of specific value of object in angularjs

I have this code:

 $scope.showReport = function(datas){
    data.post('dailyReservationReport',{date:$scope.date}).then(function (response){
        $scope.reports = response.data;
        console.log($scope.reports);

        var sum =0;
        for(var index in $scope.reports){
            if($scope.reports[index].departuredate == "2015-03-11"){
              sum += $scope.reports[index].departuredate;
            }
        }
        console.log(sum);

    })
};

The problem I was have is I want to get the sum of data with departure date which is equal to 2015-03-11. I have 2 data so the sum should output 2.

But this is the results in my console.log:

02015-03-112015-03-11

What I did wrong? Please help

Upvotes: 0

Views: 39

Answers (3)

paul
paul

Reputation: 22001

You could also count items with a certain departure date using a filter:

$filter('filter')($scope.reports, { 'departuredate': '2015-03-11' }).length

Upvotes: 0

Raj
Raj

Reputation: 31

We have to use parseInt() because our value stored in var data type it will be in string format, if we are doing addition for this then it will return Concatenation of string , So we have to use parseInt().

var sum =0;
    for(var index in $scope.reports){
        if($scope.reports[index].departuredate == "2015-03-11"){
          sum = parseInt(sum)+parseInt($scope.reports[index].departuredate); -->changed this line
        }
    }

Upvotes: 0

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100175

As per the line in your question:: "I have 2 data so the sum should output 2"., i think you just need to increment sum, as:

var sum =0;
for(var index in $scope.reports){
    if($scope.reports[index].departuredate == "2015-03-11"){
        sum++;
    }
}
console.log(sum);

Upvotes: 2

Related Questions