0

So I have an array of transactions that looks like this:

[
 {
  date: '22-03-2021,
  amount: 2,
  value: 10,
  fees: 0.1,
  type: "BUY"
  transactionId: '21412412',
 }
]

And what I want to do with the array is two things...

One is get an array of objects per date. Summing the value property of objects that are of type 'BUY' and deducting the value property from objects of type 'SELL'. Eventually I will need to deal with other transaction types, but not now...

Example: (you can see the value rise and fall, due to SELL and BUY both taking place)

[
            {
                date: "04-06-2021",
                value: 20.0,
            },
            {
                date: "05-06-2021",
                value: 28.99,
            },
            {
                date: "06-06-2021",
                value: 47.99,
            },
            {
                date: "07-06-2021",
                value: 37.99,
            },
            {
                date: "08-06-2021",
                value: 42.29,
            },
]

Two is pretty similar. I want to generate an array of objects per date but associated to a particular ticker.

Example: (value rises due to only BUY taking place)

[
 {
  TSLA: [
            {
                date: "04-06-2021",
                value: 20.0,
            },
            {
                date: "05-06-2021",
                value: 23.99,
            },
            {
                date: "06-06-2021",
                value: 42.99,
            },
            {
                date: "07-06-2021",
                value: 47.29,
            },
         ]
 }
]

Here is what ive come up with so far:

const valueByDate = useMemo(
    () =>
        holdings
            .map((data: any) => data)
            .reduce((r: any, a: any) => {
                // Find objects where ticker matches.
                r[a.date] = r[a.date] || [];
                // Push found object into array.
                r[a.date].push({ type: a.type, value: a.value });
                return r;
            }, Object.create(null)),
    [holdings],
);

// valueByDate creates an object like so...
let arr = {
    '22-05-2021': [{ type: 'SELL', value: '9' }],
    '22-06-2021': [{ type: 'SELL', value: '9' }],
    '22-07-2021': [{ type: 'SELL', value: '9' }],
};

// Sum or Deduct VALUE per date depending on TYPE
const reduce = Object.values(valueByDate).forEach((element: any) =>
    Object.values(element)
        .flat()
        .reduce((accumulator: any, currentValue: any) => {
            if (currentValue.type == 'BUY') {
                return (
                    parseFloat(accumulator) + parseFloat(currentValue.value)
                );
            } else if (currentValue.type == 'SELL') {
                return (
                    parseFloat(accumulator) - parseFloat(currentValue.value)
                );
            }
        }),
);

But I just have not been able to wrap my head around getting into the nested arrays and conditionally computing those values. Any insight would be a help.

Thank you

  • Does this answer your question? [How to group by and sum an array of objects?](https://stackoverflow.com/questions/29364262/how-to-group-by-and-sum-an-array-of-objects) – pilchard Jul 28 '21 at 08:20

1 Answers1

1

Those are the functions that I created:

type Transaction = {
    date: string,
    amount: number,
    value: number,
    fees: number,
    type: "BUY" | "SELL",
    transactionId: string
}

const transactions: Transaction[] = [
    {
        date: '22-03-2021',
        amount: 2,
        value: 10,
        fees: 0.1,
        type: "BUY",
        transactionId: '21412412',
    },
    {
        date: '22-03-2021',
        amount: 2,
        value: 10,
        fees: 0.1,
        type: "SELL",
        transactionId: '21412412',
    },
    {
        date: '22-03-2021',
        amount: 2,
        value: 10,
        fees: 0.1,
        type: "BUY",
        transactionId: '21412412',
    },
    {
        date: '23-03-2021',
        amount: 2,
        value: 10,
        fees: 0.1,
        type: "BUY",
        transactionId: '21412412',
    },
    {
        date: '23-03-2021',
        amount: 2,
        value: 10,
        fees: 0.1,
        type: "BUY",
        transactionId: '21412412',
    },
    {
        date: '23-03-2021',
        amount: 2,
        value: 10,
        fees: 0.1,
        type: "SELL",
        transactionId: '21412412',
    },
    {
        date: '23-03-2021',
        amount: 2,
        value: 10,
        fees: 0.1,
        type: "BUY",
        transactionId: '21412412',
    },
    {
        date: '23-03-2021',
        amount: 2,
        value: 10,
        fees: 0.1,
        type: "BUY",
        transactionId: '21412412',
    },
]

type DatedTransactions = { [key: string]: Transaction[] }

function getValuesByDate(transactions: Transaction[]): DatedTransactions {
    let result: { [key: string]: Transaction[] } = {}

    transactions.forEach(transaction => {
        result[transaction.date] ? result[transaction.date].push(transaction) : result[transaction.date] = [transaction]
    })

    return result
}


function getTotalValue(transactions: Transaction[]): number {
    return transactions.reduce((prev, curr) => {
        if (curr.type === "BUY") {
            return prev + curr.value
        }
        return prev - curr.value
    }, 0)
}

function getTotalValueForEveryDate(datedTransactions: DatedTransactions): { date: string, value: number }[] {
    const result: { date: string, value: number }[] = []
    Object.keys(datedTransactions).forEach(date => {
        const datedValue = { date, value: getTotalValue(datedTransactions[date]) }
        result.push(datedValue)
    })

    return result
}


console.log(getTotalValueForEveryDate(getValuesByDate(transactions)))

in order to accomplish also the last part just iterate for every ticker :)

let me know if there is something not clear

InsalataCondita
  • 301
  • 1
  • 6