Skip to content

Instantly share code, notes, and snippets.

@russo97
Forked from tiagomatosweb/transactions.js
Last active April 5, 2023 00:05
Show Gist options
  • Save russo97/955d3829d80f03dd26054c98b28180e8 to your computer and use it in GitHub Desktop.
Save russo97/955d3829d80f03dd26054c98b28180e8 to your computer and use it in GitHub Desktop.
Desafio #4 - Array de Transações
const transactions = [
{
date: '2023-03-20',
description: 'Restaurante X-Burger',
amount: -30
},
{
date: '2023-03-20',
description: 'Cinema',
amount: -45
},
{
date: '2023-03-22',
description: 'Apple store',
amount: -450
},
{
date: '2023-03-22',
description: 'Chingling accessorios',
amount: -45
},
{
date: '2023-03-23',
description: 'Café Maria josé',
amount: -7
},
{
date: '2023-04-01',
description: 'Latam',
amount: -1500
},
{
date: '2023-04-01',
description: 'Salário XYZ',
amount: 5000
},
{
date: '2023-04-01',
description: 'Canaã',
amount: -132
},
{
date: '2023-04-03',
description: 'Freelancing website',
amount: 2000
},
]
function findModuleIndexIfExists ({ modules, date }) {
return modules.findIndex(({ groupDate }) => groupDate === date)
}
function groupTransactionsByDate (transactionList) {
return transactionList
.reduce((modules, { date, description, amount }) => {
const moduleIndex = findModuleIndexIfExists({ modules, date })
if (moduleIndex > -1) {
modules[moduleIndex].transactions.push({
amount,
description
})
return modules
}
// date is not more necessary inside each object
return [
...modules, {
groupDate: date,
transactions: [{ amount, description }]
}
]
}, [])
}
console.log(groupTransactionsByDate(transactions))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment