Alphonse Alphonse - 29 days ago 18
AngularJS Question

Make sum of object properties from array

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'
}
];

Answer

You reduce the array:

var total = $scope.items.reduce(function(x,y) { return x + parseInt(y.unit_price) }, 0);