Skip to content

javascript function to convert rows into columns

I tried to search for a required solution and help but really couldn’t find something to write. I need this JavaScript function to do the following.

I have the following set of lines.

AAAAAAA
BBBBBBB
CCCCCCC
DDDDDDD

And I need to convert the above data into columns so the output would be like this.

ABCD
ABCD
ABCD
ABCD
ABCD
ABCD
ABCD

That means the rows will be converted into columns.

Anyone can help with a JavaScript or jQuery function to get the results?

Answer

You can do something like this using Array#forEach method

var data = `AAAAAAA
BBBBBBB
CCCCCCC
DDDDDDD`;

var res = [];

data.split('n').forEach(function(v) {
  v.split('').forEach(function(v1, i) {
    res[i] = (res[i] || '') + v1;
  })
});

console.log(res.join('n'));

If both input and output are in array format then you can avoid the String#split and Array#join methods

var data = [
  'AAAAAAA',
  'BBBBBBB',
  'CCCCCCC',
  'DDDDDDD'
]

var res = [];

data.forEach(function(v) {
  v.split('').forEach(function(v1, i) {
    res[i] = (res[i] || '') + v1;
  })
});

console.log(res);