I would like to create an Array stating the number of times the approved quantity goes into the original quantity (vqty) and the approved qty associated with it (aqty). The original quantity decreases after each iteration.
For example - var ApprovedQty = [680,120,450,40]; var OriginalQty = 10000;
var NewArray = [(vqty:aqty),(vqty:aqty),(vqty:aqty),(vqty:aqty)]
use some sort of for loop to generate the NewArray by sorting the original array in descending order and dividing original qty by the value in the array.
ideally its 10000/680 = 14.07 so the first value in NewArray is (14:680). Then Original qty becomes 10000 - (680x14) = 480
then 480 / 450 = 1.06 so the second value in NewArray is (1:450). Then original qty becomes 480 - (450 x1) = 30
then 30 / 120 = .25 ..since 120 is not the last available value in the orginal array, the value in the new array is (0:120) and the original qty stays 30
then 30/40 = .75..since 40 is the last value in the array, the value in the new array is (1:40)
so the newarray is [(14:680),(1:450),(0:120),(1:40)]
You could map the wanted parts by using a closure which is a function which returns a function and keeps variable total.
The code checks if the the last index is reached and takes ceil as method, otherwise floor and calls it later with the division by the value of the (previously sorted) array.
Then total gets the rest and parts is returned as result.
const
getParts = total => (value, i, { length }) => {
const
method = i + 1 === length ? 'ceil' : 'floor',
parts = Math[method](total / value);
total %= value;
return parts;
},
values = [680, 450, 120, 40],
result = values.map(getParts(10000));
console.log(...result);