Diego Resende
Diego Resende

Reputation: 83

how to move columns and put in a specific order with the google app script?

I would like to change the order of columns in a spreadsheet. For example:

Before A B C D E

After C D A E B

I have a list with the indexes of the columns in the desired order like this:

order = [1, 2, 4, 19, 8]

And I would like to go through a list and get the columns with the indexes in the order of that list and put in spreadsheet

Upvotes: 0

Views: 713

Answers (1)

Cooper
Cooper

Reputation: 64032

This would work for your example.

function reorder() {
  const ss=SpreadsheetApp.getActive();
  const sh=ss.getSheetByName('Sheet1');
  const rg=sh.getDataRange();
  const vA=rg.getValues();
  vB=vA.map(function(r){
    return [r[2],r[3],r[0],r[4],r[1]];
  });
  rg.setValues(vB);
}

Upvotes: 2

Related Questions