Home > Back-end >  How to split array of arrays into smaller parts
How to split array of arrays into smaller parts

Time:10-06

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]]

CodePudding user response:

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

CodePudding user response:

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

  • Related