0

I am trying to convert a simple array to a multidimensional array.

The Array I currently have

Array = (1, 2, 3, 4);

I would like to convert this Array to be like this

Array = ([1, 2], [3, 4]);

Any help is welcome, thanks already.

Tom Roskam
  • 23
  • 5
  • 1
    What have you tried so far? – Wimanicesir Apr 26 '21 at 07:54
  • I tried this: A.reduce((rows, key, index) => (index % 2 == 0 ? rows.push([key]) : rows[rows.length-1].push(key)) && rows, []); But this doesn't seem to do anything. – Tom Roskam Apr 26 '21 at 07:58
  • Don't "hide" relevant information in a comment. [Edit](https://stackoverflow.com/posts/67262782/edit) your question and add it there. – Andreas Apr 26 '21 at 08:02

1 Answers1

1

This worked for me:

function TwoDimensional(arr, size) 
{
  var res = []; 
  for(var i=0;i < arr.length;i = i+size)
  res.push(arr.slice(i,i+size));
  console.log(res);
}

Pretty easy when it works! Thanks

Tom Roskam
  • 23
  • 5