I have an array of objects that I need to split based on the total amount. First, calculate the sum of the total amount, then split the array based on the total amount. If the total amount is greater than or equal to 4, they will be split and the key of the object will be used as a new key.
{
25: [
{
id: 96207,
name: "Client Name",
phone: "123456789",
amount: 1,
…
},
{
id: 96484,
name: "Client Name",
phone: "123456789",
amount: 1,
…
},
{
id: 96208,
name: "Client Name",
phone: "123456789",
amount: 2,
…
},
{
id: 96261,
name: "Client Name",
phone: "123456789",
amount: 1,
…
},
{
id: 96367,
name: "Client Name",
phone: "123456789",
amount: 1,
…
},
{
id: 96431,
name: "Client Name",
phone: "123456789",
amount: 4,
…
},
{
id: 96432,
name: "Client Name",
phone: "123456789",
amount: 1,
…
},
{
id: 96483,
name: "Client Name",
phone: "123456789",
amount: 1,
…
},
{
id: 96515,
name: "Client Name",
phone: "123456789",
amount: 2,
…
},
{
id: 96536,
name: "Client Name",
phone: "123456789",
amount: 1,
…
},
{
id: 96560,
name: "Client Name",
phone: "123456789",
amount: 1,
…
}
]
}
I want to divide it like this based on the amount if the total amount is greater than or equal to 4.
{
25: [
{
id: 96207,
name: "Client Name",
phone: "123456789",
amount: 1,
…
},
{
id: 96484,
name: "Client Name",
phone: "123456789",
amount: 1,
…
},
{
id: 96208,
name: "Client Name",
phone: "123456789",
amount: 2,
…
}
]
},{
25: [
{
id: 96261,
name: "Client Name",
phone: "123456789",
amount: 1,
…
},
{
id: 96367,
name: "Client Name",
phone: "123456789",
amount: 1,
…
},
{
id: 96432,
name: "Client Name",
phone: "123456789",
amount: 1,
…
},
{
id: 96483,
name: "Client Name",
phone: "123456789",
amount: 1,
…
}
]
}, {
25: [
{
id: 96431,
name: "Client Name",
phone: "123456789",
amount: 4,
…
}
]
}, {
25: [
{
id: 96515,
name: "Client Name",
phone: "123456789",
amount: 2,
…
},
{
id: 96536,
name: "Client Name",
phone: "123456789",
amount: 1,
…
},
{
id: 96560,
name: "Client Name",
phone: "123456789",
amount: 1,
…
}
]
}
Can anyone help me achieve this result?