Rocking Ninja
Rocking Ninja

Reputation: 41

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?

Upvotes: 0

Views: 1644

Answers (4)

Brajendra Swain
Brajendra Swain

Reputation: 355

var data = ["AAAAAAA",
  "BBBBBBB",
  "CCCCCCC",
  "DDDDDDD"
];

var mapedData = data[0].split('').map(function(string, i) {
  return data.map(function(string1, i1) {
    return string1.charAt(i);
  }).join('');
});

console.log('required data ---', mapedData);

Upvotes: 0

Pranav C Balan
Pranav C Balan

Reputation: 115202

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

Upvotes: 3

mwilson
mwilson

Reputation: 12900

Per the requirement in the question, this will do it:

var arr = ["AAA", "BBB", "CCC"];
var result = ['', '', ''];
for (var i = 0; i < arr.length; i++) {
    var str = arr[i].split('');
    for (var j = 0; j < str.length; j++) {
        result[j] += str[j];
    }
}
    console.log(result);

Upvotes: 0

Sabith
Sabith

Reputation: 1656

There may be better solutions than this, Try this:

var data = ["AAAAAAA",
            "BBBBBBB",
            "CCCCCCC",
            "DDDDDDD"];

var output = [];
data.map(function(a){
    for(var i=0; i<a.length;i++){
          if(!output[i])
              output[i] = "";
         output[i] += a[i];
    }
});
console.log(output);

Upvotes: 0

Related Questions