When given an array of objects as input, the task is to identify and subtract the `transactionAmount` field value of an item that shares the same `transactionReference` (as the current item in a loop) and has a `transactionType` of 13. The final result should exclude the items with `transactionType` of 13 and perform custom actions on the remaining items.
Consider the following array:
[
{
transactionId: 45194,
transactionDate: 1579858773136,
transactionType: 13,
transactionReference: 82941,
transactionAmount: 1.21
},
{
transactionId: 45193,
transactionDate: 1579858773120,
transactionType: 11,
transactionReference: 82941,
transactionAmount: 10
},
{
transactionId: 45192,
transactionDate: 1579858763947,
transactionType: 1,
transactionAmount: 10
},
{
transactionId: 45191,
transactionDate: 1579858759085,
transactionType: 131,
transactionAmount: 2000
}
]
The function I have designed for this purpose is as follows:
transactions => transactions
.map(({
transactionId,
transactionDate,
transactionType,
transactionReference,
transactionAmount
}) => ({
transactionId,
transactionDate,
transactionType,
transactionReference,
transactionAmount: transactionAmount - Number(transactions
.filter(({
transactionId: _transactionId,
transactionReference: _transactionReference,
transactionType
}) => transactionType === 13 &&
_transactionId !== transactionId &&
transactionReference&&
_transactionReference === transactionReference
)
.map(({ transactionAmount }) => transactionAmount))
}))
.filter(({ transactionType }) => transactionType !== 13)
.map(({
transactionId,
transactionAmount,
transactionDate,
transactionType
}) => ({
id: transactionId,
amount: Number(transactionAmount).toFixed(2),
date: moment(transactionDate).format('H:mm'),
type: transactionType
}))
My goal now is to optimize this function by reducing the number of map/filter functions used while maintaining the desired outcome.
The resulting modified array is shown below:
[
{
id: 45193,
amount: "8.79",
date: 1579858773120,
type: 11
},
{
id: 45192,
amount: "10.00",
date: 1579858763947,
type: 1
},
{
id: 45191,
amount: "2000.00",
date: 1579858759085,
type: 131
}
]