const transactions = [
{
merchantName: 'Netflix',
amount: 5.99,
currency: 'GBP',
bookingDateTime: '2020-01-01T19:33:23.473Z',
},
{
merchantName: 'Petfood Co',
amount: 15,
currency: 'GBP',
bookingDateTime: '2020-01-02T19:33:23.473Z',
},
{
merchantName: 'Google',
amount: 3.99,
currency: 'GBP',
bookingDateTime: '2020-01-03T19:33:23.473Z',
},
]
function addAccumulator(transactions) {
return transactions.reduce((acc, trx) => {
if (acc.length > 0) {
trx.accumulated = acc[acc.length - 1].accumulated + trx.amount;
} else {
trx.accumulated = trx.amount;
}
acc.push(trx);
return acc;
}, []);
}
addAccumulator(transactions)
// => The Result:
// [
// {
// merchantName: 'Netflix',
// amount: 5.99,
// currency: 'GBP',
// bookingDateTime: '2020-01-01T19:33:23.473Z',
// accumulated: 5.99
// },
// {
// merchantName: 'Petfood Co',
// amount: 15,
// currency: 'GBP',
// bookingDateTime: '2020-01-02T19:33:23.473Z',
// accumulated: 20.990000000000002
// },
// {
// merchantName: 'Google',
// amount: 3.99,
// currency: 'GBP',
// bookingDateTime: '2020-01-03T19:33:23.473Z',
// accumulated: 24.980000000000004
// }
// ]
Created
April 9, 2020 16:44
-
-
Save nkhil/7fbb6b5954c45375e675395bec032ec1 to your computer and use it in GitHub Desktop.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment