I have the array:
array = [
{
id: 1,
count: 0.5
cost: 100
user: {id: 1, name: "John 1"},
type: {id: 1, name: "T1"},
period: {id: 1, name: "2021"}
},
{
id: 2,
count: 2.5
cost: 200
user: {id: 1, name: "John 1"},
type: {id: 2, name: "T2"},
period: {id: 2, name: "2022"}
},
{
id: 3,
count: 2.5
cost: 400
user: {id: 1, name: "John 1"},
type: {id: 2, name: "T2"},
period: {id: 2, name: "2022"}
},
{
id: 4,
count: 1.5
cost: 100
user: {id: 2, name: "John 2"},
type: {id: 1, name: "T1"},
period: {id: 1, name: "2021"}
},
{
id: 5,
count: 0.5
cost: 500
user: {id: 3, name: "John 3"},
type: {id: 1, name: "T1"},
period: {id: 1, name: "2021"}
}
]
I need to reduce in two different ways.
First: grouping by user, period and type, where the cost is the sum of the cost of those that match according to the previous condition.
array1 = [
{
id: 1,
count: 0.5
cost: 100
user: {id: 1, name: "John 1"},
type: {id: 1, name: "T1"},
period: {id: 1, name: "2021"}
},
{
id: 2,
count: 2.5
cost: 600
user: {id: 1, name: "John 1"},
type: {id: 2, name: "T2"},
period: {id: 2, name: "2022"}
},
{
id: 3,
count: 1.5
cost: 100
user: {id: 2, name: "John 2"},
type: {id: 1, name: "T1"},
period: {id: 1, name: "2021"}
},
{
id: 4,
count: 0.5
cost: 500
user: {id: 3, name: "John 3"},
type: {id: 1, name: "T1"},
period: {id: 1, name: "2021"}
}
]
Second: group in the same way but the cost is an element that contains the cost that match.
array2 = [
{
id: 1,
count: 0.5
cost: 100
user: {id: 1, name: "John 1"},
type: {id: 1, name: "T1"},
period: {id: 1, name: "2021"}
},
{
id: 2,
count: 2.5
cost: [{200},{400}]
user: {id: 1, name: "John 1"},
type: {id: 2, name: "T2"},
period: {id: 2, name: "2022"}
},
{
id: 3,
count: 1.5
cost: 100
user: {id: 2, name: "John 2"},
type: {id: 1, name: "T1"},
period: {id: 1, name: "2021"}
},
{
id: 4,
count: 0.5
cost: 500
user: {id: 3, name: "John 3"},
type: {id: 1, name: "T1"},
period: {id: 1, name: "2021"}
}
]
Note: for the same user, type and period, it will always be the same account
How can I do it? Thank!
Update: I tried
const array1 = array((acc, elem) => {
if (acc.some((accElem) => accElem.user.id === elem.user.id && accElem.period.id === elem.period.id && accElem.type.id === elem.type.id)) {
elem.cost = array
.filter((e) => e.user.id === elem.user.id && e.period.id === elem.period.id && e.type.id === elem.type.id)
.reduce((acc, e) => acc + e.cost, 0);
...
}
if (acc.some((accElem) => accElem.user.id === elem.user.id && accElem.period.id === elem.period.id && accElem.type.id !== elem.type.id)) {
elem.cost = array
.filter((e) => e.user.id === elem.user.id && e.period.id === elem.period.id && e.type.id === elem.type.id)
.reduce((acc, e) => e.cost, 0);
...
}
return acc.concat(elem);
}, []);