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')
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With