itwaze
itwaze

Reputation: 199

How to split an array of objects by arrays Javascript

I have an array of objects, i need to split this array to multiple arrays. If sum of element count <= 500, return these objects in array.

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

//Expected Result: array of arrays
// [[{idx: 1, count: 100}, {idx: 2, count: 200}, {idx: 3, count: 200}], [{idx: 4, count: 100}]]

Upvotes: 0

Views: 2272

Answers (4)

Mihai Matei
Mihai Matei

Reputation: 24276

You can simply do it using reduce:

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);

Upvotes: 2

Jonas Wilms
Jonas Wilms

Reputation: 138557

This can be solved quite elegantly with generators:

 function* groupTill(arr, predicate) {
   let acc = [], pred = predicate();
   for(const el of arr) {
     if(!pred(el)) {
       yield acc; acc = []; pred = predicate();
     }
     acc.push(el);
   }
   yield acc;
 }

 const result = [...groupTill(input, (total = 0) => ({ count }) => (total += count)  < 500)];

Upvotes: 1

Code Maniac
Code Maniac

Reputation: 37775

You can use reduce with flags ( These are used to track whether we need to increase the index or not )

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

let splitter = (arr) => {
  let index = 0,
    total = 0
  return arr.reduce((op, inp) => {
    if ((total + inp.count) > 500) {
      index++;
      total = 0;
    }
    total += inp.count
    op[index] = op[index] || []
    op[index].push(inp)
    return op
  }, [])
}

console.log(splitter(array))

Upvotes: 0

Maheer Ali
Maheer Ali

Reputation: 36594

You can use forEach to iterate through array and have two separate variables. One for the result array and another to hold the sum of count

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

const res = [[]]; //initialize the result array with initial subarray
let count = 0; //initialize the count to zero
//Loop through the elements of array.
array.forEach(x => {
  res[res.length - 1].push(x); //Add the the current element to the last sub array
  count += x.count //increase the temporary count  
  //if count exceeds 500
  if(count >= 500){
    //add another sub array to the end of final array
    res.push([]);
    //Reset the count to 0 
    count = 0;
  }
});
console.log(res);

Upvotes: 0

Related Questions