L Galliers
L Galliers

Reputation: 47

Google Spreadsheet - Convert multiple columns to one column

I want to loop through a set of rows in a Google Spreadsheet that look like this:

XXX 123 234 234

YYY 789 098 765

ZZZ 76 123 345

End Result Needs to Be:

XXX: 123

XXX: 234

XXX: 234

YYY: 789

YYY: 098

etc.

My current code:

function loopshoplocations(){ 
  var sheet = SpreadsheetApp.getActiveSheet(); 
  var data = sheet.getRange('A4:A8').getValues(); 
  var i=0; 
  for(i = 0; i < 4; i++){
    return ('Shop Location: ' + data[i][0]);
  }}

Upvotes: 2

Views: 119

Answers (2)

JPV
JPV

Reputation: 27242

Alternatively with a formula

=ArrayFormula( transpose(split(query(rept(left(A2:A, 3)&" ", 3),,50000), " "))&": "
&transpose(split(query(regexreplace(A2:A, "^(.+?)\s",""),,50000), " ")))

Also see this screenshot:

SCREENSHOT

Upvotes: 1

Alan Wells
Alan Wells

Reputation: 31300

This code assumes that there is a header row on row one. The data gets appended at the end of the sheet. If you want something different, the code would need to be adjusted.

function loopshoplocations() {
  var data,L,outerArray,innerArray,numberOfRows,sheet,startRow;

  startRow = 2;

  sheet = SpreadsheetApp.getActiveSheet();
  numberOfRows = sheet.getLastRow();
  data = sheet.getRange(startRow,1,numberOfRows-startRow+1,4).getValues(); 
  L = data.length;

  //Logger.log(data);

  outerArray = [];

  var i,j;
  for(i = 0; i < L; i++){

    for (j=1; j<4 ; j+=1) {//Begin count at one, not zero
      innerArray = [];//Reset
      innerArray.push(data[i][0]);
      innerArray.push(data[i][j]);
      //Logger.log(innerArray)
      outerArray.push(innerArray);
    };
  };

  sheet.getRange(numberOfRows+1,1,outerArray.length,outerArray[0].length).setValues(outerArray);
};

Upvotes: 0

Related Questions