divide array of objects to 4 arrays js

108

divide array of objects to 4 arrays js -

const array = [{idx: 1, count: 100}, {idx: 2, count: 200}, {idx: 3, count: 200}, {idx: 4, count: 100}]

const result = array.reduce((carry, item) => {
    if (!carry.array.length || carry.count + item.count > 500) {
        carry.array.push([item]);
        carry.count = item.count;
    } else {
         carry.array[carry.array.length - 1].push(item);
         carry.count += item.count;
    }
    
    return carry;
}, {array: [], count: 0}).array;

console.log(result);
 Run code snippet

Comments

Submit
0 Comments