-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.

4
  • What is the exact output? Commented Feb 20, 2023 at 9:55
  • Please see now I have edited the question - one letter from each string on a singlr line is the output Commented Feb 20, 2023 at 9: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 that would produce the output? Commented Feb 20, 2023 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. jsfiddle.net/catjrp0v - if you need less extra whitespace than what this produces, feel free to refine. Commented Feb 20, 2023 at 10:02

1 Answer 1

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'))

Sign up to request clarification or add additional context in comments.

4 Comments

Does this really needs to be answered? If I were you, I could have requested to close this question (Not my downvote).
Your code outputs R E D B L U E G R E E N, what was asked for was R B G E L R D U E E E N.
Sorry I was not able to post my question correctly as it was my first one, now see the output I want, I edited the question.
@Nitheesh thanks, I didn't see that

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.