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,
}
}