I have an array objects with quantities. In this array I have a key that tells me the value to fill (amountToFill) and a key that tells me the value already filled (amountFilled). The idea is to indicate a quantity (amount: number = 50;) and automatically amountFilled be filled with the same value as amountToFill but always reducing the value of (amount: number = 50) as the array is filled is the amount: number = 50 be equal to 0.
If the amountFilled is > 0, we must be careful when calculating the subtraction of the total amount.
initial result
amountArray =[{
option:'text',
amountToFill: 5,
amountFilled:0,
},
{
option:'text1',
amountToFill: 3,
amountFilled:1,
},
{
option:'text2',
amountToFill: 10,
amountFilled:0,
},
{
option:'text3',
amountToFill: 4,
amountFilled:1,
},
{
option:'text4',
amountToFill: 4,
amountFilled:1,
},
{
option:'text5',
amountToFill: 15,
amountFilled:0,
},
{
option:'text6',
amountToFill: 5,
amountFilled:2,
},
{
option:'text7',
amountToFill:25,
amountFilled:3,
},
{
option:'text8',
amountToFill: 15,
amountFilled:0,
},
{
option:'text9',
amountToFill: 25,
amountFilled:0,
},
{
option:'text10',
amountToFill: 5,
amountFilled:0,
}];
Desired result
amountArray1 =[{
option:'text',
amountToFill: 5,
amountFilled:5,
filled: true
},
{
option:'text1',
amountToFill: 3,
amountFilled:3,
filled: true
},
{
option:'text2',
amountToFill: 10,
amountFilled:10,
filled: true
},
{
option:'text3',
amountToFill: 4,
amountFilled:4,
filled: true
},
{
option:'text4',
amountToFill: 4,
amountFilled:4,
filled: true
},
{
option:'text5',
amountToFill: 15,
amountFilled:15,
filled: true
},
{
option:'text6',
amountToFill: 5,
amountFilled:5,
filled: true
},
{
option:'text7',
amountToFill:25,
amountFilled:12, //amount = 0
filled: true
},
{
option:'text8',
amountToFill: 15,
amountFilled:0,
filled: false
},
{
option:'text9',
amountToFill: 25,
amountFilled:0,
filled: false
},
{
option:'text10',
amountToFill: 5,
amountFilled:0,
filled: false
}];
CodePudding user response:
const amountArray =[{ option:'text', amountToFill: 5, amountFilled:0, }, { option:'text1', amountToFill: 3, amountFilled:1, }, { option:'text2', amountToFill: 10, amountFilled:0, }, { option:'text3', amountToFill: 4, amountFilled:1, }, { option:'text4', amountToFill: 4, amountFilled:1, }, { option:'text5', amountToFill: 15, amountFilled:0, }, { option:'text6', amountToFill: 5, amountFilled:2, }, { option:'text7', amountToFill:25, amountFilled:3, }, { option:'text8', amountToFill: 15, amountFilled:0, }, { option:'text9', amountToFill: 25, amountFilled:0, }, { option:'text10', amountToFill: 5, amountFilled:0, }];
let total = 50;
const res = amountArray.map(it => {
const subtract = it.amountToFill - it.amountFilled;
if (total - subtract > 0) {
total -= subtract;
return {...it, amountFilled: it.amountToFill, filled: !!total}
}
else {
const newObj = {...it, amountFilled: it.amountFilled total, filled: !!total}
total = 0;
return newObj;
}
});
console.log(res);