gpt4 book ai didi

google-apps-script - Google Script 按任何列对 2D 数组进行排序

转载 作者:行者123 更新时间:2023-12-01 08:28:50 24 4
gpt4 key购买 nike

我之前问过一个关于从数据库中检索记录的问题,这里是:Retrieving Records from a Google Sheet with Google Script

我对操作数组和创建自己的排序算法相当满意,但由于其速度,我想使用现有的 Array.sort() 方法来组织数据。我发现我可以很容易地使用它来按第一列数据对二维数组进行排序,但我找不到对不同数据列进行排序的语法,而不是第一列。

我发现的最接近的是: Google Apps Script Additional Sorting Rules 。但是,这些输入对我不起作用。这是我从以下代码中得到的,对于我的数组 tableData:

tableData.sort([{ column: 1}]);

=>TypeError: (class)@4dde8e64 不是函数,它是对象。 (第 49 行,文件“sortTablebyCol”)
tableData.sort([{column: 1, ascending: true}]);

=> TypeError: (class)@4d89c26e 不是函数,它是对象。 (第 50 行,文件“sortTablebyCol”)

选择要排序的数据列的正确语法是什么?

最佳答案

array.sort 方法可以有一个函数参数来选择要排序的部分。代码是这样的:

    array.sort(function(x,y){
var xp = x[3];
var yp = y[3];
// in this example I used the 4th column...
return xp == yp ? 0 : xp < yp ? -1 : 1;
});

编辑
根据您的评论,这里有一个小的演示功能,应该有助于理解它是如何工作的。
我没有使用短形式的 if/else 条件,而是使用传统形式并将其分成 3 行以使其更易于理解。
function demo(){
// using a full sheet as array source
var array = SpreadsheetApp.getActive().getActiveSheet().getDataRange().getValues();
Logger.log('Unsorted array = '+array);
array.sort(function(x,y){
// in this example I used the 4th column...
var compareArgumentA = x[3];
var compareArgumentB = y[3];
// eventually do something with these 2 variables, for example Number(x[0]) and Number(y[0]) would do the comparison on numeric values of first column in the array (index0)
// another example x[0].toLowerCase() and y[0].toLowerCase() would do the comparison without taking care of letterCase...
Logger.log('compareArgumentA = '+compareArgumentA+' and compareArgumentB = '+compareArgumentB);
var result = 0;// initialize return value and then do the comparison : 3 cases
if(compareArgumentA == compareArgumentB ){return result }; // if equal return 0
if(compareArgumentA < compareArgumentB ){result = -1 ; return result }; // if A<B return -1 (you can change this of course and invert the sort order)
if(compareArgumentA > compareArgumentB ){result = 1 ; return result }; // if a>B return 1
}
);
Logger.log('\n\n\nSorted array = '+array);
}
我添加了几个 Logger.log 来检查起始值、中间值和最终值。在电子表格中试试这个。
希望这会有所帮助。

关于google-apps-script - Google Script 按任何列对 2D 数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26300610/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com