使用自定义排序功能在JavaScript中对多维数组进行排序

问题描述:

在JavaScript中排序多维数组.查看其他帖子,但无法弄清楚如何将数组成员传递给自定义排序功能,该功能确定是对字符串还是数字进行排序. 自定义排序功能是这样的:

Sorting multi-dimensional array in JavaScript. Perused other posts, but can't figure out how to pass the array members to the custom sort function, which determines whether to sort a string or numbers. Custom sort function is this:

function colSort(a, b) {
    if (sortDown) dValue = 1
    else dValue = -1;

    if (isNumeric(a[sortIndex])) {
        return (b[sortIndex] - a[sortIndex]) * dValue;
    } else {
        var astring = a[sortIndex].toLowerCase();
        var bstring = b[sortIndex].toLowerCase();
        if (bstring > astring) return -dValue;
        if (bstring < astring) return dValue;
        return 0;
    }
}

数组看起来像这样:

var qbStats =[

   ['David Lea', 'GB', 343, 502, 68.3, 4643, 9.2, 45, 6, 122.5],

   ['Kevin Whyte', 'NO', 440, 622, 70.7, 5087, 8.2, 41, 13, 108.4]

]

应该可以单击HTML表格中列出数组成员的列标题,以便对单击的列进行升序/降序排序.

The column headers in a HTML table listing array members should be able to be clicked to sort ascending/descending on the clicked column.

我不知道如何在点击的索引上指示要排序的成员.

I can't figure out how to indicate members to be sorted on the clicked index.

我知道它的开头是:

qbStats.sort(colSort(a,b));

但是我不知道如何传递要在特定索引上排序的数组成员.例如:如何告诉它以'a''b'的形式在'GB''NO'上排序? 感谢您提供的任何帮助!

But I don't know how to pass the array members to be sorted on the specific index. Ex: How do I tell it to sort on 'GB' and 'NO' as 'a' and 'b'? Thanks for any help you can give!

sort()函数的比较回调由排序过程调用,并传递成对的数组元素.您无需告诉任何要比较的元素.排序过程已经知道了.

The comparison callback to the sort() function is called by the sorting process and passed pairs of array elements. You don't have to tell anything which elements to compare; the sorting process already knows that.

在您的情况下,问题在于您实际上需要每列有一个排序函数.您可以通过创建一个返回另一个函数的函数来处理该问题,该函数知道"要比较的列:

In your case, the issue is that you essentially need a sort function per column. You can handle that by creating a function that returns another function, one that "knows" which column to compare:

function byColumn(sortIndex) {
  return function colSort(a, b) {
    if (sortDown) dValue = 1
    else dValue = -1;

    if (isNumeric(a[sortIndex])) {
      return (b[sortIndex] - a[sortIndex]) * dValue;
    } else {
      var astring = a[sortIndex].toLowerCase();
      var bstring = b[sortIndex].toLowerCase();
      if (bstring > astring) return -dValue;
      if (bstring < astring) return dValue;
      return 0;
    }
  };
}

然后:

qbStats.sort(byColumn(4)); // sort by column 4

byColumn()函数只是比较器函数的简单包装.调用它时,它将返回排序过程将使用的实际函数.该函数可以访问在创建时传入的sortIndex参数,因此它本质上知道"如何比较两行.

The byColumn() function is just a simple wrapper around your comparator function. When it is called, it returns the actual function that the sort process will use. That function has access to the sortIndex parameter that was passed in at its creation time, so it intrinsically "knows" how to compare two rows.