-2

I'm using arrayofArrays[0].push() inside a for loop in order to add an Object to the Array0 inside arrayofArrays. Now I'd like that when Array0 has reached 2 element, the next element will be pushed to Array1, in order to achieve this situation:

 var arrayofArrays = [[Obj0,Obj1],[Obj2,Obj3],[Obj4,Obj5], ...];

Sample code:

var arrayofArrays = [[]];

for(data in Data){
  var Obj = {"field1":data[0], "field2":data[1], "field3":data[2] }

  arrayofArrays[0].push(Obj); // need to pass to arrayofArrays[1] when arrayofArrays[0] has 2 Obj...
}

(I don't need to split an existing array, I'm adding Object to an array, and want them to split in sub-arrays while adding them)

faccio
  • 652
  • 3
  • 16
  • 1
    What is `ecc`? Is it a variable? – trincot Feb 13 '23 at 21:22
  • 1
    @trincot Sorry it's an italian word, it's a way of saying "and so on..." – faccio Feb 13 '23 at 21:28
  • I get the impression `Data` is an array with objects/arrays. In that case you are looking for chunking an existing array (after mapping it), making this a duplicate. – trincot Feb 13 '23 at 21:39
  • Data is a JSON response, containing some data object. So they are all different – faccio Feb 13 '23 at 21:40
  • a JSON response is just an object/array structure, so that doesn't really tell us anything useful. Either way, taking a collection and creating an array of arrays with each sub array containing n items from the collection is just chunking, covered by the dupe. – Kevin B Feb 13 '23 at 21:41
  • I'm not taking a ready collection and creating an Array of arrays. I'm creating some Objects from data response and then putting them in the arrays – faccio Feb 13 '23 at 21:48

1 Answers1

-1

Here is a functional programming approach to your question to unflatten an array:

const arr = Array.from(Array(6).keys()); // [0, 1, 2, 3...]
let t;
let arrOfArr = arr.map((v, idx) => {
  if(idx % 2) {
    return [t, v];
  } else {
    t = v;
    return null;
  }
}).filter(Boolean);
console.log({
  arr,
  arrOfArr,
});

Note: Array.from(Array(6).keys()) is just for demo. Replace this with any array of objects you like

Peter Thoeny
  • 7,379
  • 1
  • 10
  • 20