I have an array of sizes that I’d like to reduce + chunk based on custom logic using ramda:
const sizes = [ { size: 30 }, { size: 10 }, { size: 40 }, { size: 20 }, { size: 20 }, ];
If the cumulative total exceeds the 50
threshold I would like to chunk them up, so that the result becomes:
const threshold = 50; // 30 + 10 <= 50 // 40 <= 50 // 20 + 20 <= 50 const result = [40, 40, 40];
I’ve tried using reduceWhile
and splitWhen
but with no luck so far
Advertisement
Answer
Reduce the array to a new array. On each iterate, check if the current number + last item is greater than the max. If it is, set the current number as the last item. If not add the current number to the last item:
const sumMax = (max, arr) => arr.reduce((acc, n) => (acc.at(-1) ?? 0) + n > max ? [...acc, n] : [...acc.slice(0, -1), (acc.at(-1) ?? 0) + n] , [] ) const sizes = [{ size: 30 },{ size: 10 },{ size: 40 },{ size: 20 },{ size: 20 }]; const result = sumMax(50, sizes.map(o => o.size)) console.log(result)