Google脚本按任意列排序二维数组 [英] Google Script sort 2D Array by any column

查看:127
本文介绍了Google脚本按任意列排序二维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我曾问过一个关于从数据库中检索记录的早期问题,在这里:使用Google脚本从Google表格中检索记录



我很熟悉操作数组并创建自己的排序算法,但我想要使用现有的 Array.sort()方法来组织数据,因为它的速度很快。我发现我可以很容易地使用这个来按照第一列数据对2D数组进行排序,但是我找不到排序在除第一列以外的其他列数据的语法。

我发现的最接近的是: Google Apps脚本其他排序规则。然而,这些投入并没有为我工作。这是我为以下代码得到的,对于我的数组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];
//在这个例子中,我使用了第4列...
return xp == yp?0:xp< yp?-1 :1;
});






编辑



在你的评论之后,这里有一个小的演示函数,它应该有助于理解它是如何工作的。



不使用简短形式if / else condition I使用传统的表单并将其分成3行以便于理解。

 函数demo(){
//使用完整的工作表作为数组源
var array = SpreadsheetApp.getActive()。getActiveSheet()。getDataRange()。getValues();
Logger.log('Unsorted array ='+ array);
array.sort(function(x,y){
//在这个例子中我使用了第四列...
var compareArgumentA = x [3];
var compareArgumentB = y [3];
//最终对这两个变量做一些事情,例如Number(x [0])和Number(y [0])将对数组中第一列的数值进行比较(index0)
//另一个例子x [0] .toLowerCase()和y [0] .toLowerCase()会在不考虑letterCase的情况下进行比较...
Logger.log('compareArgumentA ='+ compareArgumentA +'和compareArgumentB ='+ compareArgumentB);
var result = 0; //初始化返回值,然后进行比较:3例
if(compareArgumentA == compareArgumentB){return result} ; //如果相等返回0
if(compareArgumentA< compareArgumentB){result = -1; return result}; //如果A< B返回-1(当然可以改变它并颠倒排序顺序)
if(compareArgumentA> compareArgumentB){result = 1; return结果}; //如果a> B返回1
}
);
Logger.log('\\\
\\\
\\\
Sorted array ='+ array);
}

我添加了一对Logger.log来检查开始,中间和最终值。在电子表格中试试这个。



希望这会有所帮助。


I had a asked an earlier question about retrieving records from a database, here: Retrieving Records from a Google Sheet with Google Script

I'm fairly comfortable with manipulating arrays and creating my own sorting algorithms, but I want to use the existing Array.sort() method to organize the data because of its speed. I'm finding that I can easily use this to sort a 2D array by the first column of data, but I can't find the syntax to sort on a different column of data, other than the first.

The closest that I've found is this: Google Apps Script Additional Sorting Rules. However, these inputs haven't worked for me. Here is what I get for the following code, for my array, tableData:

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

=>TypeError: (class)@4dde8e64 is not a function, it is object. (line 49, file "sortTablebyCol")

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

=> TypeError: (class)@4d89c26e is not a function, it is object. (line 50, file "sortTablebyCol")

What is the proper syntax for choosing which column of data to sort on?

解决方案

The array.sort method can have a function argument to choose on what part you want to sort. Code goes like this :

    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;
    });


EDIT

Following your comment, here is a small demo function that should help to understand how this works.

Instead of using short form if/else condition I used the traditional form and splitted it in 3 lines to make it easier to understand.

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);
}

I added a couple of Logger.log to check starting, intermediate and final values. Try this in a spreadsheet.

Hoping this will help.

这篇关于Google脚本按任意列排序二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆