0

Hi I'm I really don't know how to add all the numbers when I get the jsonObjectArray I'm using _.map in lodash and angular for each for getting the data in jsonObjectArray

$scope.dataNumbers = _.map(result.numbers);
  angular.forEach($scope.dataNumbers, function(value, key) {
  console.log(value.allNumbers)
})

When I console this is the response (8.17, 32.01, 37.45).

I tried to add them like this Number(value.allNumbers) + Number(value.allNumbers) but the result is (16.34, 64.02 , 74.9)

Sorry for the basic question

Rahi.Shah
  • 1,305
  • 11
  • 20
VLR
  • 312
  • 1
  • 4
  • 18
  • Possible duplicate of [How to find the sum of an array of numbers](https://stackoverflow.com/questions/1230233/how-to-find-the-sum-of-an-array-of-numbers) – str Jun 22 '17 at 07:28

6 Answers6

2

Use reduce instead

const result = {
    numbers: [8.17, 32.01 , 37.45]
};

const allNumbers = result.numbers.reduce((acc, curr) => {
    return acc + Number(curr);
}, 0);

console.log(allNumbers);
Erazihel
  • 7,295
  • 6
  • 30
  • 53
1

You could save it to a $scope or a global js var

$scope.sumOfNum = 0;
$scope.dataNumbers = _.map(result.numbers);
  angular.forEach($scope.dataNumbers, function(value, key) {
  $scope.sumOfNum += Number(value.allNumbers);
  console.log(value.allNumbers);
  console.log($scope.sumOfNum);
});
Sajal
  • 4,359
  • 1
  • 19
  • 39
1

you can use reduce function in javascript ,

var total=$scope.dataNumbers.reduce(function(total,num){
 return total+num
});
Srinivas ML
  • 732
  • 3
  • 12
1

Using angular.forEach to loop the result.numbers and add them

var _total;
angular.forEach(result.numbers, function(value) {
  _total += Number(value);
})
console.log(_total);

Or use reduce

$scope.total = result.numbers.reduce(function(total, curr) {
    return total + curr;
});
daan.desmedt
  • 3,752
  • 1
  • 19
  • 33
1

if you want to calculate the sum of the numbers that are stored in the allNumbers field of $scope.dataNumbers, try

var sum = _.sum(_.map($scope.dataNumbers, 'allNumbers'));
0

Usual way to sum the json object array values

var totalNumbers = 0;
angular.forEach($scope.dataNumbers, function(value, key) {
  totalNumbers += parseInt(value);
});
console.log(totalNumbers);
Vivek
  • 1
  • 2