Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Push from one two-dimensional array to another two-dimensional array

I have an array like this:

arr1 [
  [
    '    ', '[H] ',
    '    '
  ],
  [
    '[W] ', '[B] ',
    '    '
  ],
  [
    '[S] ', '    ',
    '[M]'
  ]
]

How to push the 0 indexed elements of each array in arr1 into arr2[0], the 1 indexed elements of each array in arr1 into arr2[1] and so on, like this:

arr2 [
  [
    '    ', '[W] ',
    '[S] '
  ],
  [
    '[H] ', '[B] ',
    '    '
  ],
  [
    '    ', '    ',
    '[M]'
  ]
]

this method

let arr2 = []
 for (let i = 0; i< arr1.length; i++) {
   for (let j of arr1[i]) {
     arr2[i].push(j[i])
     //or arr2[i].push(j)
   }
 }

throws an error

arr2[i].push(j[i]) //or arr2[i].push(j) the same error
       ^
TypeError: Cannot read properties of undefined (reading 'push')
like image 569
В Х Avatar asked Oct 26 '25 15:10

В Х


1 Answers

Presumably you start arr2 as an empty array, so you need to initialize each subarray.

const arr1 = [
  ['    ', '[H] ', '    '],
  ['[W] ', '[B] ', '    '],
  ['[S] ', '    ', '[M]'],
];

const arr2 = [];

for (let i = 0; i < arr1.length; i++) {
  for (const arr of arr1) {
    if (!arr2[i]) arr2[i] = [];
    arr2[i].push(arr[i]);
  }
}

console.log(arr2);
like image 158
Chris Hamilton Avatar answered Oct 29 '25 03:10

Chris Hamilton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!