Skip to content
Advertisement

how to perform sum/minus operation on an array of objects, based on similar values(not properties) in an array of objects [closed]

i have an array of objects like this:

i/p:

JavaScript

now i want to perform sum operation on amount property, based on same property values, and minus operation on amount property based to reverse matching property values(i,e from,to), reduce the array to :

o/p:

JavaScript

note: resultant array amount property shouldn’t be negative

i have tried few of the methods, but cant able to achieve this.

Advertisement

Answer

Maybe this will be helpful:

JavaScript

In the .reduce function I collate all payments between two partners into an accounts object with “acounts” named after “from-to” this name is always established in alphabetical order, so, if I encounter a payment {from:"b", to:"a", amount:123} I swap the order and make the amount negative:

JavaScript

After having done this I walk through the accounts object with Object.entries. This will allow me to separate the account names into from and to partners again. This time I check, whether the amount payable between the partners would be negative. If so I swap the order of the partners (ft) and multiply the amonut (a) by -1:

JavaScript
Advertisement