JSFiddle - React, Tailwind, and code Playground
by sundaramkumar
June 24, 2020
HTML
Sum object of array by same element
<div ng-app='MyModule' ng-controller='MyController'>
<p>travelerTotal = {{travelerTotal}}</p>
<p>totalAges = {{totalAges}}</p>
</div>
JavaScript
angular.module('MyModule', [])
.controller( 'MyController', function($scope){
$scope.traveler = [
{ description: 'Senior', Amount: 50},
{ description: 'Senior', Amount: 50},
{ description: 'Adult', Amount: 75},
{ description: 'Child', Amount: 35},
{ description: 'Infant', Amount: 25 }
];
$scope.people = [
{ name: 'Dave', Age: 23},
{ name: 'Davina', Age: 37},
{ name: 'Bob', Age: 42},
{ name: 'Clare', Age: 18}
];
$scope.sum = function(items, prop){
return items.reduce( function(a, b){
return a + b[prop];
}, 0);
};
$scope.travelerTotal = $scope.sum($scope.traveler, 'Amount');
$scope.totalAges = $scope.sum($scope.people, 'Age');
});