Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 …

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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) });
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading