1

I have to get the sum of unit_price numbers. How can I do that?

The array looks like this:

 $scope.items = [
    {
        id: '1',
        name: 'Phone',
        quantity: '1',
        unit_price: '200'
    },
    {
        id: '2',
        name: 'IPhone',
        quantity: '1',
        unit_price: '240'
    }
];
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Alphonse
  • 661
  • 1
  • 12
  • 29

3 Answers3

8

You reduce the array:

var total = $scope.items.reduce(function(x,y) { return x + parseInt(y.unit_price) }, 0);
David Hedlund
  • 128,221
  • 31
  • 203
  • 222
1

Try this:

var sum = 0;
angular.forEach($scope.items, function(value, key){
    sum = sum + value.unit_price;
});
Carlos Laspina
  • 2,013
  • 4
  • 27
  • 44
0

Although you can use reduce for this, there's no reason to and it's easy to get wrong. (reduce is useful if you're doing functional programming with predefined, reusable reducers; otherwise, it's just overcomplicated.)

A simple loop is all you need, perhaps with some destructuring:

let sum = 0;
for (const {unit_price} of $scope.items) {
    sum += +unit_price;
//         ^−−−−−−−−−−− converts your strings to numbers
}

Live Example:

const $scope = {};
$scope.items = [
    {
        id: '1',
        name: 'Phone',
        quantity: '1',
        unit_price: '200'
    },
    {
        id: '2',
        name: 'IPhone',
        quantity: '1',
        unit_price: '240'
    }
];

let sum = 0;
for (const {unit_price} of $scope.items) {
    sum += +unit_price;
}

console.log(sum);

Re converting your unit_price strings to numbers: My answer here lists your various options for doing that, with some pros and cons for each. I've used the unary + above, but there are other options.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875