Table2 Custom Sorting

Problem

I received a question on how to use the table2 custom sorting functionality.

The problem to solve was that each object in the array has a key ‘price’ which stores the price as a string. When sorting the column, they were being sorting by their string values rather than their numeric value.

Solution

I referred to this documentation for my implementation.

Assuming you have a column in your table data called price which is a string of digits, you can add this to your table options:

  "customSorting": {
    "price_function": "var ascending = arguments[0]; return function(a,b){if (ascending) return parseFloat(a.price) >= parseFloat(b.price) ? 1 : -1; return parseFloat(a.price) <= parseFloat(b.price) ? 1 : -1;}"
  }

Explanation

The price key in the customSorting object is expected to be a function, so I use _function to convert it accordingly.
(Initially was using _calcf, but ran into issues with argument passing)

I start by grabbing the ascending key out of the arguments passed by the sorter. This key refers to which direction the price is being sorting. We need this for the inner function.

Inside the inner function, I’m comparing a and b, which are two objects of your table data passed in by the sorter. The sorter expects a 1 or a -1 to know which object to place in front of the other.

Since this changes based of the direction of the sort (ascending or descending), we can utilize the variable we set earlier and return conditionally.

To solve the issue of the price being of type string, I parse them as floats so that they can be compared correctly.

I hope this example may help someone create their own custom sorting functionality in their tables.

EDIT: Here is another example sorting a name field by the last name:

"name_function": "var ascending = arguments[0]; return function(a,b){if (ascending) return a.name.split(' ')[1] >= b.name.split(' ')[1] ? 1 : -1; return a.name.split(' ')[1] <= b.name.split(' ')[1] ? 1 : -1;}"

Thanks Andrew, this is awesome and just what IU was looking for :wink:

If you need to be able to sort by a date using a similar method here is the code

"customSorting": {
                        "date_function": "var ascending = arguments[0];return function(a, b) {if (ascending) return moment(a.date, 'M/D/YYYY').isAfter(moment(b.date, 'M/D/YYYY')) ? 1 : -1;return moment(b.date, 'M/D/YYYY').isAfter(moment(a.date, 'M/D/YYYY')) ? 1 : -1;}"
                    }
1 Like