1

I have certain array. I have to convert it's columns into rows. I have one working solution. I create a newArr in order to copy values into it. But it doesn't work! I have to make a copy, then clear the original array, so that I can copy the values ​​into it again. Why can't they be correctly inserted into newArr?

function rowToColumn(board) {
  // let newArr = Array(9).fill([])           //why i can't insert values in this arr?)
  let arr = JSON.parse(JSON.stringify(board)) //copy original array
  board.forEach(el => {                       //clear original array
    el.splice(0, 9)
  });
  
  for(let i = 0; i < 9; i++) {                //insert values into cleared original array
    for(let j = 0; j < 9; j++) {
      board[i].push(arr[j].splice(0, 1)[0])
    }
  }
  return board
}

console.log(rowToColumn([  [5, 3, 4, 6, 7, 8, 9, 1, 2], 
                           [6, 7, 2, 1, 9, 0, 3, 4, 9],
                           [1, 0, 0, 3, 4, 2, 5, 6, 0],
                           [8, 5, 9, 7, 6, 1, 0, 2, 0],
                           [4, 2, 6, 8, 5, 3, 7, 9, 1],
                           [7, 1, 3, 9, 2, 4, 8, 5, 6],
                           [9, 0, 1, 5, 3, 7, 2, 1, 4],
                           [2, 8, 7, 4, 1, 9, 6, 3, 5],
                           [3, 0, 0, 4, 8, 1, 1, 7, 9]]))

output array must be:

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

Sorry for stupid questions. Have a nice day:)

Pavel
  • 33
  • 7

0 Answers0