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.