I have an array of n objects in it. Each object has names as id, quantity, price and total. All of these have significance in solving this problem.
How can I create new arrays where sum of all total
of their objects doesn't exceed 150.
My array:
let array = [{id: 1, quantity: 5, price: 10, total: 50}, {id: 2, quantity: 3, price: 100, total: 300}]
Expected result:
array1 = [{id: 1, quantity: 5, price: 10, total: 50}, {id: 2, quantity: 1, price: 100, total: 100}]
array2 = [{id: 2, quantity: 1, price: 100, total: 100}]
array3 = [{id: 2, quantity: 1, price: 100, total: 100}]
Conditions:
- As mentioned, sum of
total
s in new arrays mustn't exceed 150 - value of
total
must always be product ofquantity
andprice
in that object - object must keep dividing itself into new objects with smaller quantities until above conditions are met
quantity
must be an integer
i tried this.
const itemsFinals = [];
const maxTotal = 150;
let totalGroup = 0;
for (i = 0; i < itemComprobantes.length; i++) {
if((itemComprobantes[i].total + totalGroup) < maxTotal){
itemsFinals.push(itemComprobantes[i]);
totalGroup += itemComprobantes[i].total;
}
}