-6
a = ['RED', 'BLUE', 'GREEN]

output = R B G

         E L R

         D U E

           E E

             N

How to achieve this output ? (I believe we have to use 2D array methods)

I tried 2 nested for loops for a[i][j], but did'nt get the desired result.

Konrad
  • 21,590
  • 4
  • 28
  • 64
Aman Jain
  • 1
  • 2
  • 2
    Please post the relevant code attempts that you have made – Nitheesh Feb 20 '23 at 09:54
  • What is the exact output? – Sebastian Simon Feb 20 '23 at 09:55
  • Please see now I have edited the question - one letter from each string on a singlr line is the output – Aman Jain Feb 20 '23 at 09:59
  • @AmanJain JavaScript doesn’t have a data structure such as _“one letter from each string on a singlr line”_. What is the exact [literal](//developer.mozilla.org/en/docs/Glossary/Literal) that would produce the output? – Sebastian Simon Feb 20 '23 at 10:00
  • Determine the length of the longest word first, then loop over that length, inside loop over all three input strings - and if there still is a character at that position, output that, else output a space. https://jsfiddle.net/catjrp0v/ - if you need less extra whitespace than what this produces, feel free to refine. – CBroe Feb 20 '23 at 10:02

1 Answers1

0

const a = ['RED', 'BLUE', 'GREEN']

// length of the longest string
const max = Math.max(...a.map(s => s.length))

// create 2D array 3 x 1
const output = [...Array(max)].map(() => [])

// for each character
for (let i = 0; i < max; i += 1) {
  // for each string
  for (let j = 0; j < a.length; j += 1) {
    output[i][j] = a[j][i]
  }
}

// pretty print
console.log(output.map(e => e.map(c => c || ' ').join(' ')).join('\n'))
Konrad
  • 21,590
  • 4
  • 28
  • 64