Search code examples
javascriptarraysmathjavascript-objects

Add and join doubles in an array of objects


I hold all the expenses data in a JS Object as shown...

var transactions = {
  "date": "1-1-2023",
  "amount": "850",
  "name": "rent",
  "category": "housing",
  "notepad": ""
},
{
  "date": "1-1-2023",
  "amount": "91",
  "name": "electric",
  "category": "housing",
  "notepad": ""
},
{
  "date": "1-1-2023",
  "amount": "gas",
  "name": "83",
  "category": "housing",
  "notepad": ""
},
{
  "date": "1-1-2023",
  "amount": "50",
  "name": "car insurance",
  "category": "transportation",
  "notepad": ""
}

How can I calculate and all all the money together spent in housing and put it in an array (same with the other categories)?

The goal is to have something like ...

var groups = ['housing', 'transportation']
var expenses = ['1000', '50']

Solution

  • Could you do something like this?

    const transactions = [
      {
        date: "1-1-2023",
        amount: "850",
        name: "rent",
        category: "housing",
        notepad: "",
      },
      {
        date: "1-1-2023",
        amount: "91",
        name: "electric",
        category: "housing",
        notepad: "",
      },
      {
        date: "1-1-2023",
        amount: "83",
        name: "gas",
        category: "housing",
        notepad: "",
      },
      {
        date: "1-1-2023",
        amount: "50",
        name: "car insurance",
        category: "transportation",
        notepad: "",
      },
    ];
    
    /**
     * This function calculates the expenses total for each category in the transactions array
     * @param transactions
     * @returns { expenseGroups: [string], expenseTotals: [number] }
     * @example
     */
    function calculateExpenses(transactions) {
      const expenseGroups = [];
      const expenseTotals = [];
    
      transactions.forEach((transaction) => {
        const { category, amount } = transaction;
        const index = expenseGroups.indexOf(category);
    
        if (index === -1) {
          expenseGroups.push(category);
          expenseTotals.push(Number(amount));
        } else {
          expenseTotals[index] += Number(amount);
        }
      });
    
      return { expenseGroups, expenseTotals };
    }
    
    console.log({ result: calculateExpenses(transactions) });