Search code examples
javascriptreactjsfunctionreact-propsuse-state

Is there a better way to find properties of object in an array


I am improving my coding skills. I wrote a code and it works fine. But I think it could be written better.

Here is are the codes and a bit of explanation,

I use the code below to setState for an array named transactions

useEffect(() => {
  TransactionService.getTransactions().then(data => {
    setTransactions(data.transactions);
  });
}, []);

I needed to sum an object in the transaction array so I wrote this code.

let a = transactions,
  total = 0;

for (var i = 0; i < a.length; i++) {
  total += a[i].amount;

  console.log('total', total);
};

Then, use the code by calling it like this {total}

<h1>{total}</h1>

Then I needed the value of a property in the last object within the array so I wrote this

var array1 = transactions;
var first = array1[array1.length - 1];

console.log(first);

const payment = { ...first };

And subsequently used it like this

<h1>{payment.amount}</h1>

The code works fine Please any idea on how to write this better. Thanks


Solution

  • This works better for me. thanks,

        
      const lastTransaction = transactions[transactions.length - 1];
      let lastPayment = ({ ...lastTransaction }).amount;
      const today = new Date();
      let lastMonth = today.getMonth() - 1;
      let relevantYear = today.getYear();
      let thisMonth = today.getMonth();
    
      const lastMonthTransactions = transactions.filter(i => {
      const date = new Date(i.date);
        return date.getMonth() === lastMonth && date.getYear() === relevantYear;
      }).reduce((prev, curr) => prev + parseFloat(curr.amount), 0)

    @Tr1stan @Emile Bergeron