-1

I have something like this, an array of arrays where each array has a 7 values

const arrays = [[1,2,3,4,5,6,7],[8,9,10,11,12,13,14]]

What's the most efficient way to split this into array of arrays where each array will have a 2 values and last array of arrays will hold the remaining 1 element, like this

[[1,2], [8,9]] [[3,4], [10,11]] [[5,6], [12,13]] [[7], [14]]
macrog
  • 2,085
  • 1
  • 22
  • 30
  • 1
    Does this answer your question? [How to split a long array into smaller arrays, with JavaScript](https://stackoverflow.com/questions/7273668/how-to-split-a-long-array-into-smaller-arrays-with-javascript) – champion-runner Oct 05 '21 at 18:54
  • This question is already answered [here](https://stackoverflow.com/questions/7273668/how-to-split-a-long-array-into-smaller-arrays-with-javascript) – champion-runner Oct 05 '21 at 18:55

2 Answers2

0

You can use array#reduce and array#forEach to split your array based on size.

const arr = [[1,2,3,4,5,6,7],[8,9,10,11,12,13,14]],
      size = 2,
      result = arr.reduce((r, a, i) => {
        a.forEach((v,j) => {
          const idx = Math.floor(j/size);
          r[idx] = r[idx] || [];
          r[idx][i] = r[idx][i] || [];
          r[idx][i].push(v);
        });
        return r;
      },[]);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51
0

It doesn't look that efficient, but it works.

const arrays = [[1,2,3,4,5,6,7],[8,9,10,11,12,13,14]];

// number of sub arrays
var numsubarr = Math.ceil(arrays[0].length / 2);

// parring up the vaules
var arr1 = arrays.map(arr => Array.from(Array(numsubarr).keys()).map(i => arr.slice(i*2, i*2+2)));

// combining the two arrays
var arr2 = Array.from(Array(numsubarr).keys()).map(i => [arr1[0][i],arr1[1][i]]);

console.log(arr2);
chrwahl
  • 8,675
  • 2
  • 20
  • 30