Skip to content Skip to sidebar Skip to footer

Sorting A Multi-dimensional Array In Javascript Using A Custom Sort Function

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

Solution 1:

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 = 1else 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;
      return0;
    }
  };
}

And then:

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

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.

Solution 2:

Maybe this is something for you. The function returns for any case the right function to compare.

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

functionsort(column, sortOrder, isNumber) {
    if (isNumber) {
        if (~sortOrder) {
            returnfunction (a, b) {
                return a[column] - b[column];
            }
        } else {
            returnfunction (a, b) {
                return b[column] - a[column];
            }
        }
    } else {
        if (~sortOrder) {
            returnfunction (a, b) {
                return a[column].localeCompare(b[column]);
            }
        } else {
            returnfunction (a, b) {
                return b[column].localeCompare(a[column]);
            }
        }
    }
}

qbStats.sort(sort(0, 1, false)); // sort 0th column, ascending by stringdocument.write('<pre>' + JSON.stringify(qbStats, 0, 4) + '</pre>');

qbStats.sort(sort(2, -1, true)); // sort 2th column, descending by numberdocument.write('<pre>' + JSON.stringify(qbStats, 0, 4) + '</pre>');

Post a Comment for "Sorting A Multi-dimensional Array In Javascript Using A Custom Sort Function"