如何预先排序数字而不是搞砸格式?

时间:2015-10-07 23:28:23

标签: javascript google-apps-script google-sheets google-apps

我正在编写一个自定义函数,它将返回一个数组数组:

function tester(col){
  var rows = [ // this gives me an error on sorting, so turn numbers to strings
    [4,2,3,"Tom"],
    [0,8,9,"Bill"],
    [5,7,1,"Bob"],
    [1,2,3,"Charlie"]
  ];

  rows = [ // turning numbers to strings screws up formatting
    ["4","2","3","Tom"],
    ["0","8","9","Bill"],
    ["5","7","1","Bob"],
    ["1","2","3","Charlie"]
  ];
   rows.sort(function(a, b) {
   return a[col].localeCompare(b[col]); // sort by column passed by user
  });
  return rows;
}

如上所述,如果我传入数字,我会收到错误:

TypeError: Cannot find function localCompare in object

如果我将这些数字转换成字符串,我可以排序但是用户无法格式化数字...显示更多的小数,逗号,将它们变成百分比等等。如何解决这个问题?

编辑:

我已经尝试过Buzinas / Kriggs的建议,但它似乎对数字和否定词进行词汇排序,而其他人则没有正确排序。我现在有(注意负4和750):

function tester(col){
  var rows = [
    [-4,2,3,"Tom"],
    [0,8,9,"Bill"],
    [5,750,1,"Bob"],
    [1,2,3,"Charlie"]
  ];

  rows.sort(function(a, b) {
     return a[col].toString().localeCompare(b[col].toString());
  });

  return rows;
}

1 个答案:

答案 0 :(得分:0)

<强>更新

由于您希望按数字排序(如果它们是数字),如果它们是字符串,则按字符串排序,您可以这样做:

function tester(col){
  var rows = [
    [4,2,3,"Tom"],
    [0,8,9,"Bill"],
    [5,7,1,"Bob"],
    [1,2,3,"Charlie"]
  ];

  rows.sort(function(a, b) {
    if (typeof a[col] === 'number')
      return a[col] > b[col];
    return a[col].localeCompare(b[col]);
  });

  return rows;
}