While it is technically possible to utilize reduce
in this scenario, there is really no need for it and the chances of making mistakes are high. (reduce
is more appropriate for advanced functional programming with predefined reducers, otherwise, it just adds unnecessary complexity.)
A straightforward loop will suffice, possibly incorporating some destructuring:
let total = 0;
for (const {unit_price} of $scope.items) {
total += +unit_price;
// ^−−−−−−−−−−− converting strings to numbers
}
Check out this live example:
const $scope = {};
$scope.items = [
{
id: '1',
name: 'Laptop',
quantity: '2',
unit_price: '800'
},
{
id: '2',
name: 'Tablet',
quantity: '1',
unit_price: '400'
}
];
let total = 0;
for (const {unit_price} of $scope.items) {
total += +unit_price;
}
console.log(total);
When transforming your unit_price
strings into numbers: my solution here outlines different approaches along with their pros and cons. I have utilized the unary +
above, but alternate methods exist.