Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

73
Views
Chunk array based on conditional logic using ramda

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

about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

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)

about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!