Here is an alternative method to achieve the same result. I cannot comment on the performance comparison with PSL's method, but in my opinion, this code is easier to understand for someone not very proficient in javascript.
function groupByName(names) {
inputArray = names.split('\n');
outputArray = {};
for (i = 0; i < inputArray.length; i++) {
var keyValuePair = inputArray[i].split(',');
var key = keyValuePair[0];
var count = Number(keyValuePair[1]);
// create element if it doesn't exist
if (!outputArray[key]) outputArray[key] = 0;
// increment by value
outputArray[key] += count;
}
return outputArray;
}
This function will generate an object with grouped names and counts:
{
"John": 6,
"Jane": 8
}
To display the name of each property along with its value using ng-repeat:
<li ng-repeat="(key, value) in groupedNames">
The total for {{key}} is {{value}}
</li>
The javascript code is relatively simple, depending on the number of name-value pairs. You can even eliminate the manual calculation button and use a $watch
on values
to automatically update totals with every change.
$scope.$watch('values', function() {
$scope.groupedNames = groupByName($scope.values);
});