简体   繁体   English

Google Apps 脚本:为什么这种排序不起作用?

[英]Google Apps Script: Why Does this Sorting Not Work?

new to google apps script and trying to find the second highest value in a range.谷歌应用程序脚本的新手并试图找到范围内的第二大值。 When I input a range like [45, 101, 100, 40] the value returned is 101 .当我输入像[45, 101, 100, 40]这样的范围时[45, 101, 100, 40]返回的值为101 Clearly the sort() isn't working as it is just returning the second value in the range.显然sort()不起作用,因为它只是返回范围内的第二个值。 What am I missing?我错过了什么?

function second_max(range) {
  if (range) {
    var arr = [];
    for (var i = 0; i < range.length; i++) {
      arr.push(range[i]);
    }
    arr.sort();
    Logger.log(arr);
    return arr[1];
  }

}

change arr.sort() to arr.sort(function(a, b){return ab}) .arr.sort()更改为arr.sort(function(a, b){return ab})

It doesn't sort because it thinks it's a string.它不排序,因为它认为它是一个字符串。 For example, [1, 5, 2, 100, 500, 250, 60, 55, 100000] will be sorted to [1, 100, 100000, 2, 250, 5, 500, 55, 60].例如,[1, 5, 2, 100, 500, 250, 60, 55, 100000] 将被排序为 [1, 100, 100000, 2, 250, 5, 500, 55, 60]。

So, you'd better to implement subtraction callback function inside of sort() so that you can get the right result.所以,最好在sort()内部实现减法回调函数,这样才能得到正确的结果。

check this out: https://www.w3schools.com/jsref/jsref_sort.asp看看这个: https : //www.w3schools.com/jsref/jsref_sort.asp

Issue:问题:

  • range is a two dimensional array - array of arrays(eg: [[45], [101], [100], [40]] ). range是一个二维数组 - 数组数组(例如: [[45], [101], [100], [40]] )。 arr.sort can sort only numbers. arr.sort只能对数字进行排序。

Solution(s):解决方案:

You can try any of the following:您可以尝试以下任一方法:

  • You can easily use inbuilt formulas like SORTN to do the same:您可以轻松地使用SORTN等内置公式来执行相同的操作:

     =INDEX(SORTN(A1:A20,2),2)
  • Pass a compareFunction to parse the array and sort.传递一个compareFunction来解析数组并排序。

  • Flat ten the array and use Math.max将数组Flat并使用 Math.max

Snippet:片段:

// Will only work for vertical rows as horizontal ranges like A1:C1 looks like [[1,2,3]]; Modify it accordingly.
function second_max(arr) {
  return arr.sort(([a],[b])=>b-a)[1][0];
}

/* Works with any 2D array*/
function second_max2(arr) {
  let flatArr = arr.flat();
  let max1 = Math.max(...flatArr);
  return Math.max(...flatArr.filter(num=>num !== max1))
}

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

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