0

https://datatables.net/examples/basic_init/table_sorting.html

$(document).ready(function() {
    $('#example').DataTable( {
        "order": [[ 3, "desc" ]]
    } );
} );

The example in the documentation uses array of arrays as a source and defines ordering by specifying indices.

How can I specify default ordering when the source is array of objects.

I tried to write it as

        "order": [[ "attribute_name", "desc" ]]

but it doesn't work. I get this error

Uncaught TypeError: Cannot read property 'aDataSort' of undefined

1 Answer 1

1

According to the documentation the first parameter of the order function (or first position in the array of the order object in your case) must be the index number of the column you wish to sort on.

To get around this, you could instead set the value of the property to a function that returns the index of the column you want. So for example:

$(document).ready(function() {
  function findColumn(input) {
    return function(element) {
      return element.sTitle === input;
    }
  }

  var myDataTable = $('#example').DataTable();
  var columnIWant = "Office";
  var indexOfThatColumn = myDataTable.context[0].aoColumns.find(findColumn(columnIWant)).idx;

  myDataTable.order([indexOfThatColumn, "desc"]);
});

Admittedly this is pretty ugly (though functional!), but with some refactoring this could be a decent solution.

Sign up to request clarification or add additional context in comments.

1 Comment

This looks like a very interesting solution! Thanks. I was thinking of creating an object to map names to indices but I could see how difficult it would be to maintain later when I need to change anything.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.