How do I pre-sort numbers and not screw up the formatting?

笑着哭i 提交于 2019-12-13 05:46:15

问题


I have a custom function I am writing that will return an array of arrays:

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

As noted, if I pass in numbers I get an error:

TypeError: Cannot find function localCompare in object

If I turn those numbers into strings I can sort but then the user isn't able to format the numbers...show more decimals, commas, turn them into percentages, etc. How do I resolve this?

EDIT:

I've tried the suggestion by Buzinas/Kriggs but it seems to do a lexical sort for numbers and negatives and others don't sort properly. I now have (notice the negative 4 and 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:


UPDATE

Since you want to sort by number if they are numbers, and by string if they are strings, you can do:

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


来源:https://stackoverflow.com/questions/33004116/how-do-i-pre-sort-numbers-and-not-screw-up-the-formatting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!