简体   繁体   English

JavaScript / Google 脚本 - 将“行”数组转换为“列”数组

[英]JavaScript / Google Script - Transpose “Row” Array into “Column” Array

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我正在尝试将“行”数组(或一维数组)转置为“列”数组(或数组,该数组是一个包含单个 arrays 的数组),以允许我将值设置为单个列(向下多行),而不是如果它是跨多列的一行

I attempted using a push loop and a map function but neither attempt succeeded:我尝试使用推送循环和 map function 但均未成功:

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:转置尝试#1:

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

Output for Attempt # 1: Output 用于尝试#1:

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

Transpose attempt # 2:转置尝试#2:

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

Output for attempt # 2: Output 用于尝试#2:

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

The intended output I would like to have is:我想要的预期 output 是:

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

Would there be a way to achieve the intended output?有没有办法实现预期的 output?

In your script of var items = ss.getRange(16,4,1,endRange).getValues() , items is 2 dimensional array like [[value1, value2, value3,,,]] .在您的var items = ss.getRange(16,4,1,endRange).getValues()脚本中, items是二维数组,如[[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:参考:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM