0

I am doing a data manipulation practice with an array of objects, which I want to add income and expenses of all the objects of the array and return an object, I do the sum in a "correct" way but it is dirty and I would like to know If there is a cleaner way to do the code.
This is the array of objects:

const projects = [
  {
    amount: 26800,
    type: 'expense',
  },
  {
    amount: 2600,
    type: 'income',
  },
  {
    amount: 6890,
    type: 'expense',
  },
  {
    amount: 901800,
    type: 'expense',
  },
  ...
];

This my code javascript:

const dato = () => {
  let income = 0;
  let expense = 0;
  const total = projects.map((project) => {
    income += project.type === 'income' ? project.amount : 0;
    expense += project.type === 'expense' ? project.amount : 0;
    return {
      income,
      expense,
      byTotal: {
        total: income - expense,
      },
    };
  });

  console.log(total[total.length - 1]);
};

The object I want to create is the following.

{
  income: 3900000,
  expense: 2293600,
  byTotal: {
    total: 1606400,
  }
}
1
  • you can also use reduce Commented Jul 14, 2022 at 6:34

3 Answers 3

1

You can use reduce instead of map, and use Object.assign to sum the amounts in an accumulator object:

const projects = [{amount: 26800,type: 'expense',},{amount: 2600,type: 'income',},{amount: 6890,type: 'expense',},{amount: 901800,type: 'expense',},];

const dato = () => {
    const {income, expense} = projects.reduce(
        (acc, {type, amount}) => Object.assign(acc, {[type]: acc[type] + amount}),
        {income: 0, expense: 0}
    );
    const total = {income, expense, byTotal: {total: income - expense}};
    console.log(total);
};

dato();

Sign up to request clarification or add additional context in comments.

Comments

1

You can use reduce

const total = projects.reduce(
    (acc, cur) => {
        if (cur.type == 'income') acc.income += cur.amount;
        if (cur.type == 'expense') acc.expense += cur.amount;
        acc.byTotal.total += acc.income - acc.expense;
        return acc;
    },
    {
        income: 0,
        expense: 0,
        byTotal: {
            total: 0,
        },
    }
);

Comments

0

You can make use of a reducer by subtracting or adding the amount based on the type in one line:

const projects = [{
    amount: 26800,
    type: 'expense',
  },
  {
    amount: 2600,
    type: 'income',
  },
  {
    amount: 6890,
    type: 'expense',
  },
  {
    amount: 901800,
    type: 'expense',
  }
];

const sum = projects.reduce(
  (amount, object) =>
  amount + (object.type === "expense" ? -object.amount : object.amount),
  0
);

console.log(sum)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.