Search code examples
javascriptplaid

How can I calculate the sum of values of Plaid API transaction array in Java Script?


Apologies for the potentially silly question - I'm fairly new to coding/JavaScript.

I am using Plaid's sandbox environment to pull in transactional data in a sandbox environment. Right now, I define the following as transactionData:

    let transactionsData = [];
transactions.forEach(function(account) {
  account.transactions.forEach(function(transaction) {
    transactionsData.push({
      account: account.accountName,
      date: transaction.date,
      category: transaction.category[0],
      name: transaction.name,
      amount: transaction.amount
    });
  });
});

I can successfully render the individual transactions row by row in a material table like so:

    const transactionsColumns = [
  { title: "Account", field: "account" },
  { title: "Date", field: "date", type: "date", defaultSort: "desc" },
  { title: "Name", field: "name" },
  { title: "Amount", field: "amount", type: "numeric" },
  { title: "Category", field: "category" }
];

          <MaterialTable
            columns={transactionsColumns}
            data={transactionsData}
            }}

I know this has to be super simple, but all I want to do is sum the transactionsData and render that single summed value elsewhere on my page. If I write transactionsData.length I can receive the count of the transactions quite easily. I have tried the following somewhat similar syntax but have not found it to work:

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

Any help would be much appreciated.


Solution

  • Here's total, using Array.prototype.reduce:

    const transformed = [{"account":"Navy Federal Credit Union","date":"2020-01-01","category":"Travel","name":"United Airlines","amount":500},{"account":"Navy Federal Credit Union","date":"2019-12-30","category":"Travel","name":"Uber 072515 SF**POOL**","amount":6.33},{"account":"Navy Federal Credit Union","date":"2019-12-27","category":"Food and Drink","name":"Tectra Inc","amount":500}]
    
    const unrounded = transformed.reduce(
      (acc, { amount }) => acc + amount,
      0
    );
    
    const roundCents = amount => Math.round(amount * 100) / 100;
    
    const total = roundCents(unrounded);
    
    console.log(total);

    A plainer version of the above, with no destructuring:

    const transformed = [{"account":"Navy Federal Credit Union","date":"2020-01-01","category":"Travel","name":"United Airlines","amount":500},{"account":"Navy Federal Credit Union","date":"2019-12-30","category":"Travel","name":"Uber 072515 SF**POOL**","amount":6.33},{"account":"Navy Federal Credit Union","date":"2019-12-27","category":"Food and Drink","name":"Tectra Inc","amount":500}]
    
    const unrounded = transformed.reduce(
      (acc, transaction) => acc + transaction.amount,
      0
    );
    
    const roundCents = amount => Math.round(amount * 100) / 100;
    
    const total = roundCents(unrounded);
    
    console.log(total);

    And here's how to transform transactionsData with Array.prototype.flatMap and Array.prototype.map, rather than forEach:

    const transactionsData = [{ accountName: 'a1', transactions: [{ date: '2020', category: ['c1'], name: 'n1', amount: 100 }, { date: '2020', category: ['c2'], name: 'n2', amount: 100 }]}, { accountName: 'a2', transactions: [{ date: '2020', category: ['c3'], name: 'n3', amount: 100 }, { date: '2020', category: ['c4'], name: 'n4', amount: 100 }]}]
    
    const transformed = transactionsData.flatMap(({ accountName, transactions }) =>
      transactions.map(({ date, category, name, amount }) => ({
          account: accountName,
          date,
          category: category[0],
          name,
          amount
        })
      )
    );
    
    console.log(transformed)

    And again, a plainer version, without the destructuring:

    const transactionsData = [{ accountName: 'a1', transactions: [{ date: '2020', category: ['c1'], name: 'n1', amount: 100 }, { date: '2020', category: ['c2'], name: 'n2', amount: 100 }]}, { accountName: 'a2', transactions: [{ date: '2020', category: ['c3'], name: 'n3', amount: 100 }, { date: '2020', category: ['c4'], name: 'n4', amount: 100 }]}]
    
    const transformed = transactionsData.flatMap(account =>
      account.transactions.map(transaction => ({
          account: account.accountName,
          date: transaction.date,
          category: transaction.category[0],
          name: transaction.name,
          amount: transaction.amount
        })
      )
    );
    
    console.log(transformed)

    Array.prototype.map is the correct method to use if you want to create a new array from an existing one, and Array.prototype.flatMap is the correct method to use if you need a flattened array and map would generate a nested one.