Better way to sum a property value in an array

后端 未结 16 1485
遥遥无期
遥遥无期 2020-11-22 02:41

I have something like this:

$scope.traveler = [
            {  description: \'Senior\', Amount: 50},
            {  description: \'Senior\', Amount: 50},
             


        
16条回答
  •  一生所求
    2020-11-22 03:35

    I know that this question has an accepted answer but I thought I'd chip in with an alternative which uses array.reduce, seeing that summing an array is the canonical example for reduce:

    $scope.sum = function(items, prop){
        return items.reduce( function(a, b){
            return a + b[prop];
        }, 0);
    };
    
    $scope.travelerTotal = $scope.sum($scope.traveler, 'Amount');
    

    Fiddle

提交回复
热议问题