I am trying to create a directive to find sum of largest integer in the response data.
directive:-
.filter('sumByKey', function() {
return function(data, key) {
if (typeof(data) === 'undefined' || typeof(key) === 'undefined') {
return 0;
}
var sum = 0;
for (var i = data.length - 1; i >= 0; i--) {
sum += parseInt(data[i][key]);
}
return sum;
};
In the above I am able to do sum of total values present in the data
.
There is a javascript function to calculate to find largest value and do sum of largest value example:-
var array = [5, 5, 7,7,8,8];
var max = array[0], total = 0;
array.forEach((a)=>{
if(a==max){
total+=max;
}
else if(a>max){
max = total = a;
}
});
console.log("total:"+total);
So here data
is my array
. Want to do same calculation. I tried to implement that on directive , but getting error.
EDIT:-
.filter('sumByKey', function() {
return function(data, key) {
if (typeof(data) === 'undefined' || typeof(key) === 'undefined') {
return 0;
}
for(let child of data.DeploymentTime) {
console.log(child);
var i = child;
var array = [].slice.call(i);
var max = array, total = 0;
array.forEach((a)=>{
if(a==max){
total+=max;
}
else if(a>max){
max = total = a;
}
});
return total;
});
I am getting is not iterable
javascript error
As per your code, you are doing a lot of stuff which is mainly not required here below an example of working filter that achieves your requirement :
app.controller('demo', function($scope, $filter) {
$scope.value = $filter('sumByKey')([{age:1},{age:2},{age:2}],'age');
})
app.filter('sumByKey', function() {
return function(input,key) {
if (typeof(input) === 'undefined' || typeof(key) === 'undefined') {
return 0;
}
var total = 0,max = Number.MIN_SAFE_INTEGER;
angular.forEach(input,function(a){
if(a[key]==max){
total+=max;
}
else if(a[key]>max){
max = total = a[key];
}
});
return total;
}
});