Chuck Villavicencio
Chuck Villavicencio

Reputation: 393

substract an element of an array after multiply two elements on the same array

I'm getting info from an api, and i multiply two elements from the response, and then, sum the result. This is my code so far:

function forTest(){
            $http.get('/api/DaApi?di=' + '2018-11-01' + '&df=' + '2018-11-01')
            .then(function(data){
                $scope.result = data.data.Response;

                $scope.multiplyResult = $scope.result.map(x => x.Cost * x.Quantity).reduce((a, b) => a + b, 0);
        }

Everything works perfect, but now i have to make another operation before the total sum. Let's say now i have 3 elements: Cost, Quantity and Discount:

[{Quantity: 2, Cost: 1000, Discount: -100},
{Quantity: 3, Cost: 2000, Discount: -500},
{Quantity: 2, Costo: 3130, Discount: -120}]

And now i need to multiply Quantity per Cost, and substract the Discount(which is already a negative number). After multiply and substract, i have to sum all the results. How can i make the substraction? Inside of map i have to make the subsraction? Something like:

$scope.multiplyResult = $scope.result.map(x => (x.Cost * x.Quantity) + x.Discount)).reduce((a, b) => a + b, 0);

Or must be inside of the reduce?

Someone can help me please, i'm a little far to understand the use of map and reduce. I'm using javascript and AngularJs.

Thanx in advance.

Upvotes: 0

Views: 42

Answers (2)

eag845
eag845

Reputation: 1013

I think it was a typo.

let arr = [{Quantity: 2, Cost: 1000, Discount: -100},
{Quantity: 3, Cost: 2000, Discount: -500},
{Quantity: 2, Cost: 3130, Discount: -120}];

let sum = arr.map(x => (x.Cost * x.Quantity) + x.Discount).reduce((a,b)=>a+b,0)
console.log(sum);

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386680

You could calculate and sum in a single loop by taking a destructuring assignment for the needed properties and then add to sum the price.

$scope.multiplyResult = $scope.result
    .reduce((sum, { Cost, Quantity, Discount }) => sum + Cost * Quantity + Discount, 0);

Upvotes: 0

Related Questions