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

183
Views
Split array of objects into new array or objects based on given value

I have an array of objects that look something like this;

value = [{id:1, count:50},{id:1, count:25}]

I need below three senario as below. scenario :- 1

result1 = [
  [ { id: 1, qty: 25 } ],
  [ { id: 1, qty: 25 } ],
  [ { id: 2, qty: 25 } ]
]

scenario:- 2

  result2 = [ [ { id: 1, qty: 50 }, { id: 2, qty: 25 } ] ]

scenario:-3

[ [ { id: 1, qty: 50 }, { id: 2, qty: 15 } ], [ { id: 2, qty: 10 }] ]

I have resolved scenario 1 and scenario 2, however getting logic issues in scenario 3.

please see below JS code

let temp = 0;
        let arr = [];
        let result = [];
        let receive_list = [
            { id: 1, qty: 50 },
            { id: 2, qty: 25 },
        ]
        const packing_weight = 65;
            receive_list.forEach(item => {
            let availableQty = item.qty;//50
            while (availableQty > 0) {
                if (availableQty >  packing_weight) {
                    arr.push({ id: item.id, qty: packing_weight });
                    availableQty = availableQty - packing_weight; //25
                    temp += packing_weight;
                }
                else {
                    arr.push({ id: item.id, qty: availableQty });
                    temp += availableQty;
                    availableQty = 0;
                }
                if(temp === packing_weight){
                    result.push(arr);
                    temp = 0;
                    arr = [];
                }
            }
        })

I need below result which I am getting empty array result = [] instead of below result [ [ { id: 1, qty: 50 }, { id: 2, qty: 15 } ], [ { id: 2, qty: 10 }] ]

about 4 years ago · Juan Pablo Isaza
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!