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

3 Answers 3

8

You reduce the array:

var total = $scope.items.reduce(function(x,y) { return x + parseInt(y.unit_price) }, 0);
Sign up to request clarification or add additional context in comments.

1 Comment

This is the solution :)
1

Try this:

var sum = 0;
angular.forEach($scope.items, function(value, key){
    sum = sum + value.unit_price;
});

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.