1

Good afternoon,

I am attempting transpose a "row" array (or 1D array) into a "column" array (or array that is one array containing individual arrays within it) to allow me to set values to a single column (downward multiple rows) instead if it being one row across multiple columns

I attempted using a push loop and a map function but neither attempt succeeded:

function myFunction2() {

  var ss=SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Source1");

  var lastColumn = ss.getLastColumn()

  var endRange = lastColumn-3

  //Retrieve values into array named "items"
  var items = ss.getRange(16,4,1,endRange).getValues()

Transpose attempt # 1:

  var colArray = [];
    for (var i=0; i<items.length; i++)
    {
      colArray.push([items[i]]);
    }
}

Output for Attempt # 1:

[[[item1, item2, item3, item4, item5]]]

Transpose attempt # 2:

  var colArray = items.map(function (el){
      return [el];
  });

Output for attempt # 2:

[[[item1, item2, item3, item4, item5]]]

The intended output I would like to have is:

[[item1], [item2], [item3], [item4], [item5]]

Would there be a way to achieve the intended output?

1
  • Transpose attempt #2 works and outputs as your intended output: jsfiddle.net/z5kj17wa Commented Mar 11, 2021 at 0:59

1 Answer 1

1

In your script of var items = ss.getRange(16,4,1,endRange).getValues(), items is 2 dimensional array like [[value1, value2, value3,,,]]. So, when your script is modified, it becomes as follows.

From:

  var colArray = [];
    for (var i=0; i<items.length; i++)
    {
      colArray.push([items[i]]);
    }
}

To:

var colArray = [];
for (var i = 0; i < items[0].length; i++) {
  colArray.push([items[0][i]]);
}

And,

From:

var colArray = items.map(function (el){
    return [el];
});

To:

var colArray = items[0].map(function (el){
  return [el];
});

Note:

  • Or, when you want to transpose the values including the several rows and columns, you can also use the following script.

      const colArray = items[0].map((_, i) => items.map(row => row[i]));
    

References:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.