在按子阵列排序之前应用转置
为了按列分隔数据,我建议使用转置方法,以便您可以轻松地按行形式对数据进行排序。您可以使用以下方法:
function runBothScripts() {
const ss = SpreadsheetApp.getActive();
const sheet = ss.getSheetByName('Sheet2');
const originalValues = sheet.getRange('M5:N7').getValues(); //combine the ranges of both columns here
var transposedValues = originalValues[0].map((col, i) => originalValues.map(row => row[i])); //transpose method to sort the columns easier as rows
var randomizedValues = transposedValues.map(x=>x.sort((a, b) => 0.5 - Math.random()));
var output = randomizedValues[0].map((col, i) => randomizedValues.map(row => row[i])); //transpose method to return to original position
sheet.getRange('N9:M11').setValues(output); //combine the ranges of both output columns here
}
为此,我使用了以下示例数据:
通过转换数据(脚本采用自
this post
),您可以轻松地对从以下转换而来的数据进行排序:
[[“a”、“红色”]、[“b”、“绿色”]、[[“c”、“黄色”]]
致:
[[“a”、“b”、“c”]、[“红色”、“绿色”、“黄色”]]
由于值现在按子阵列分组,因此可以很容易地对其进行排序,从而隔离列值。之后,使用额外的转置方法将数组返回到其原始维度。
注:
由于这是对较小样本量的随机化,因此预计输出与输入完全相同的可能性更高。因此,如果你不想要当前的输出,你最好重新运行脚本。
工具书类