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
  • 155,085
  • 27
  • 166
  • 222
Alphonse
  • 621
  • 8
  • 28

3 Answers3

8

You reduce the array:

var total = $scope.items.reduce(function(x,y) { return x + parseInt(y.unit_price) }, 0);
David Hedlund
  • 125,403
  • 30
  • 199
  • 217
1

Try this:

var sum = 0;
angular.forEach($scope.items, function(value, key){
    sum = sum + value.unit_price;
});
Carlos Laspina
  • 1,843
  • 4
  • 24
  • 43
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
  • 959,406
  • 173
  • 1,780
  • 1,769