Reputation: 101
I am getting json data from server through $http.get method. in the data one of the field called Credits, it contains negative values and positive numbers. any one can help me how can i get negative numbers in seperate total and positive numbers in separate totals??
Array.prototype.sum = function (prop) {
var total = 0
for (var i = 0, _len = this.length; i < _len; i++) {
total += parseInt(this[i][prop])
}
return total
}
$scope.totalCreadit = function (arr) {
return arr.sum("credits");
}
this function is giving me the totals but i need to separate in total for negative values and positive values.
thanks in advance.
Upvotes: 0
Views: 1607
Reputation: 222582
You could use filter
and reduce
method,
var arr = [ 1, 2, 3, 4, 5, -2, 23, -1, -13, 10, -52 ],
positive = arr.filter(function (a) { return a >= 0; }),
negative = arr.filter(function (a) { return a < 0; }),
sumnegative = negative.reduce(function (a, b) { return a + b; }),
sumpositive = positive.reduce(function (a, b) { return a + b; });
console.log(sumnegative);
console.log(sumpositive);
Upvotes: 1