first post, new to coding in js. I am trying to create a function that takes a (2) string array as an input such as ["coderbyte", "3"], the first string being any random string. The second string represents the number of rows the function should create in a 2D array. The function should then print the first string in a zig zag pattern such as the following:
c r e o e b t d y
The function should then return the word formed by combining the characters as it iterates through each row, eg "creoebtdy". I have declared the empty array and using a while loop, managed to place the first three characters in the correct places in the array using the following code:
//initialize array of arrays of empty spaces
rows = Number(strArr[1])
columns = strArr[0].length
//console.log(rows)
//console.log(columns)
a = Array(rows).fill('').map(x => Array(columns).fill(''))
let i = 0
//a[0][0]= strArr[0][0]
while (i <= rows-1) {
a[i][i]= strArr[0][i]
//console.log(a)
i++
}
//console.log(a)
//let j = i - 2
//console.log(i)
while (i >= rows && i < rows*2) {
let j = i - 2
a[j][i] = strArr[0][i]
i++
j--
}
console.log(a)
}
stringChal3(["coderbyte", "3"])
I am getting a "TypeError: Cannot set property '5' of undefined" error at line 23 (a[j][i]...) when trying to place "e" and "r" in the array. I am unsure of how to fix the error. All help is much appreciated!