I am trying to retrieve the first, and proceeding letters in an array of strings. What I have been working on is looping over each item and then printing arr[i][0], but this does not work for the proceeding letters.
For example:
Input:
'
00100
11110
10110
Output:
011010111011000
Basically, I want to traverse vertically, not horizontally.
function solution(s) {
// transform string into array
let arr = s.split('\n')
for (let i = 0; i < arr.length; i ) {
// log the first, then proceeding letter in each string
console.log(arr[i][0])
}
}
console.log(
solution(`00100
11110
10110
`)
)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
Use a nested for
loop:
function solution(s) {
// transform string into array
let arr = s.split('\n')
for (let i = 0; i < arr[0].length; i ) {
for(let f = 0; f < arr.length; f ){
console.log(arr[f][i])
}
}
}
console.log(solution(`00100
11110
10110`))
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
You could split and split again for each row and map a new array with the characters transposed.
function solution(s) {
return s
.split('\n')
.reduce((r, s) => [...s].map((c, i) => (r[i] || '') c), [])
.join('');
}
console.log(solution('00100\n11110\n10110'));
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>