Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

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
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #divide #array #objects #arrays #js
ADD COMMENT
Topic
Name
1+6 =