-4

I would like to generate a 2-D array in javascript representing the grid below.Tried different things but in vain. enter image description here

  • So an array nested within an array `var arr = [ [1,2,3], [4,5,6], [7,8,9] ];` What is your issue? – epascarello Feb 29 '16 at 13:59
  • 2
    Possible duplicate of [How can I create a two dimensional array in JavaScript?](http://stackoverflow.com/questions/966225/how-can-i-create-a-two-dimensional-array-in-javascript) – ManoDestra Feb 29 '16 at 14:00
  • I tried declaring the rows as a single array and then add them in a 2-D array. Then as I can see the "diagonals" have the same numbers. Hence Im trying to loop into the first row and set the different rows. – Yovan Juggoo Feb 29 '16 at 14:01
  • You really should be adding more info into your question with an [edit]. As it is right now it is very unclear what you want to achieve, and what the relation between the rows/columns/cells is. – Kyll Feb 29 '16 at 14:02

1 Answers1

0

Basically, each row in your matrix is the previous row shifted to the left:

var source = [0,9,4,6,8,2,7,1,3,5]

matrix = source.map(function(_, index) {
  return source.slice(index).concat(source.slice(0, index))
});

matrix.map(row => document.write(row + "<br>"));
georg
  • 211,518
  • 52
  • 313
  • 390