1

Is it possible to use a higher order javascript function to resize single dimension array into a multi-dimensional array (i.e. 1x6 to 2x3) or do i have to work around with for loops?

Do you have any code examples to resize [0,1,2,3,4,5] to [[0,1,2],[3,4,5]]?

Eddie
  • 26,593
  • 6
  • 36
  • 58
jumper384
  • 23
  • 2
  • There doesn't seem to be any function that could resize an array the way you want. You need to to that with loops, I could write an example code that contains loops if you want. – Ümit Aparı Oct 06 '18 at 16:36

2 Answers2

1

For a real 2D array, you could flat it and take the values with a generator by using new arrays' mapping.

function resize(array, i, j) {
    var gen = array.reduce((a, b) => a.concat(b))[Symbol.iterator]();
    
    return Array.from({ length: i }, _ => Array.from({ length: j }, _ => gen.next().value));
}

console.log(resize([[0, 1, 2, 3, 4, 5]], 2, 3));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
-1

Using Ramda https://ramdajs.com/docs/#splitEvery

R.splitEvery(3, [0,1,2,3,4,5]); //=> [[0,1,2],[3,4,5]]
Anthony Raimondo
  • 1,621
  • 2
  • 24
  • 40