Carol.Kar
Carol.Kar

Reputation: 5355

DataTable - Make values sortable

I am using datatables to create my table.

Find below my minimum viable example:

jQuery(document).ready(($) => {
  function loadHardware() {

    var results = {
      "profRigHardware": [{
          "unique_id": "us-sdfasdfsad",
          "title": "Product1",
          "permalink": "http://test.com/computer-hardware/product1/",
          "manufacturer": "test",
          "smallImg": "http://test.com/content/uploads/2018/07/product1.jpg",
          "currency": "$",
          "price": "5700.00",
          "watt": 620,
          "hashRatePerSecond": 0.05,
          "daily_netProfit": "61.06",
        },
        {
          "unique_id": "us-asdfasd4e",
          "title": "Product2",
          "permalink": "http://test.com/computer-hardware/product2/",
          "manufacturer": "test",
          "smallImg": "http://test.com/content/uploads/2018/07/product2.jpg",
          "currency": "$",
          "price": "5700.00",
          "watt": 620,
          "hashRatePerSecond": 0.05,
          "daily_netProfit": "161.06",
        },
        {
          "unique_id": "us-asdfasd4e",
          "title": "Product3",
          "permalink": "http://test.com/computer-hardware/product3/",
          "manufacturer": "test",
          "smallImg": "http://test.com/content/uploads/2018/07/product3.jpg",
          "currency": "$",
          "price": "5700.00",
          "watt": 620,
          "hashRatePerSecond": 0.05,
          "daily_netProfit": "-6.06",
        },
        {
          "unique_id": "us-asdfasd4e",
          "title": "Product4",
          "permalink": "http://test.com/computer-hardware/product4/",
          "manufacturer": "test",
          "smallImg": "http://test.com/content/uploads/2018/07/product4.jpg",
          "currency": "$",
          "price": "5700.00",
          "watt": 620,
          "hashRatePerSecond": 0.05,
          "daily_netProfit": "-116.06",
        },
        {
          "unique_id": "us-asdfasd4e",
          "title": "Product5",
          "permalink": "http://test.com/computer-hardware/product5/",
          "manufacturer": "test",
          "smallImg": "http://test.com/content/uploads/2018/07/product5.jpg",
          "currency": "$",
          "price": "5700.00",
          "watt": 620,
          "hashRatePerSecond": 0.05,
          "daily_netProfit": "-0.06",
        }
      ]
    };
    const rentabilityHtml = function(daily_netProfit) {
      if (daily_netProfit < 0) {
        return `<div style="color:red;"><b>$${daily_netProfit}/day</b></div>`
      } else {
        return `<div style="color:green;"><b>$${daily_netProfit}/day</b></div>`
      }
    }
    //transform data set
    let dataSet = results.profRigHardware.map((item, i) => [
      `<img src="${ item.smallImg }" alt="${ item.title }" height="42" width="42"> 
         <a href="${item.permalink}" target="_blank">
            ${item.title}
             </a>`,
      `${ rentabilityHtml(parseFloat(item.daily_netProfit)) }`,
    ])

    //remove spinner
    $(".loading").remove()

    $('#allHardwareOverview').DataTable({
      data: dataSet,
      destroy: true,
      iDisplayLength: 25,
      responsive: true,
      "bInfo": false,
      "order": [
        [1, 'desc']
      ],
      columns: [{
          title: "Model"
        },
        {
          title: "Profitability"
        }
      ],
      "initComplete": function(settings, json) {
        $('#datatablediv').css('opacity', 1);
      }
    });
  }
  // init
  loadHardware();
});
<link href="https://cdn.datatables.net/1.10.18/css/jquery.dataTables.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdn.datatables.net/1.10.18/css/dataTables.bootstrap4.min.css" rel="stylesheet" />
<script src="https://cdn.datatables.net/1.10.18/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.18/js/dataTables.bootstrap4.min.js"></script>

<div class="tab-pane fade show active" id="all" role="tabpanel" aria-labelledby="all-tab">
  <div class="table-responsive overflow-x:auto;">
    <table id="allHardwareOverview" style="width:100%; float: left;" class="table table-bordered"></table>
  </div>
</div>

As you can see my datatable does not order my profitability values correctly.

The correct order should look like the following:

| Model     | Profitability     |
|---------- |---------------    |
| Product2  | $161.06/day       |
| Product1  | $61.06/day        |
| Product5  | $-0.06/day        |
| Product3  | $-6.06/day        |
| Product4  | $-116.06/day      |

As you can see the order is created by the profitability column.

Any suggestions why my table os not ordered correctly?

I appreciate your replies!

Upvotes: 1

Views: 50

Answers (2)

Luca Kiebel
Luca Kiebel

Reputation: 10096

You can add a render function to your Profitability column and only then transform the data into HTML, change the definition of your dataSet to:

let dataSet = results.profRigHardware.map((item, i) => [
  `<img src="${ item.smallImg }" alt="${ item.title }" height="42" width="42"> 
         <a href="${item.permalink}" target="_blank">
            ${item.title}
             </a>`,
  parseFloat(item.daily_netProfit), // add the element as the number it is
])

and then add a rowCallback function to your datatable that changes the html of the column:

$('#allHardwareOverview').dataTable({
  ...
  rowCallback: function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {
    $('td:eq(1)', nRow).html(rentabilityHtml($('td:eq(1)', nRow).html()));
  }

});

Or, in full:

$(document).ready(($) => {
  function loadHardware() {

    var results = {
      "profRigHardware": [{
          "unique_id": "us-sdfasdfsad",
          "title": "Product1",
          "permalink": "http://test.com/computer-hardware/product1/",
          "manufacturer": "test",
          "smallImg": "http://test.com/content/uploads/2018/07/product1.jpg",
          "currency": "$",
          "price": "5700.00",
          "watt": 620,
          "hashRatePerSecond": 0.05,
          "daily_netProfit": "61.06",
        },
        {
          "unique_id": "us-asdfasd4e",
          "title": "Product2",
          "permalink": "http://test.com/computer-hardware/product2/",
          "manufacturer": "test",
          "smallImg": "http://test.com/content/uploads/2018/07/product2.jpg",
          "currency": "$",
          "price": "5700.00",
          "watt": 620,
          "hashRatePerSecond": 0.05,
          "daily_netProfit": "161.06",
        },
        {
          "unique_id": "us-asdfasd4e",
          "title": "Product3",
          "permalink": "http://test.com/computer-hardware/product3/",
          "manufacturer": "test",
          "smallImg": "http://test.com/content/uploads/2018/07/product3.jpg",
          "currency": "$",
          "price": "5700.00",
          "watt": 620,
          "hashRatePerSecond": 0.05,
          "daily_netProfit": "-6.06",
        },
        {
          "unique_id": "us-asdfasd4e",
          "title": "Product4",
          "permalink": "http://test.com/computer-hardware/product4/",
          "manufacturer": "test",
          "smallImg": "http://test.com/content/uploads/2018/07/product4.jpg",
          "currency": "$",
          "price": "5700.00",
          "watt": 620,
          "hashRatePerSecond": 0.05,
          "daily_netProfit": "-116.06",
        },
        {
          "unique_id": "us-asdfasd4e",
          "title": "Product5",
          "permalink": "http://test.com/computer-hardware/product5/",
          "manufacturer": "test",
          "smallImg": "http://test.com/content/uploads/2018/07/product5.jpg",
          "currency": "$",
          "price": "5700.00",
          "watt": 620,
          "hashRatePerSecond": 0.05,
          "daily_netProfit": "-0.06",
        }
      ]
    };
    const rentabilityHtml = function(daily_netProfit) {
      if (daily_netProfit < 0) {
        return `<div style="color:red;"><b>$${daily_netProfit}/day</b></div>`
      } else {
        return `<div style="color:green;"><b>$${daily_netProfit}/day</b></div>`
      }
    }
    //transform data set
    let dataSet = results.profRigHardware.map((item, i) => [
      `<img src="${ item.smallImg }" alt="${ item.title }" height="42" width="42"> 
         <a href="${item.permalink}" target="_blank">
            ${item.title}
             </a>`,
      //`${ rentabilityHtml(parseFloat(item.daily_netProfit)) }`,
      parseFloat(item.daily_netProfit)
    ])

    //remove spinner
    $(".loading").remove()


    $('#allHardwareOverview').dataTable({
      data: dataSet,
      destroy: true,
      iDisplayLength: 25,
      responsive: true,
      "bInfo": false,
      "order": [
        [1, 'desc']
      ],
      columns: [{
          title: "Model"
        },
        {
          title: "Profitability"
        }
      ],
      "initComplete": function(settings, json) {
        $('#datatablediv').css('opacity', 1);
      },
      rowCallback: function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {
        $('td:eq(1)', nRow).html(rentabilityHtml($('td:eq(1)', nRow).html()));
      }
    });
  }
  // init
  loadHardware();
});
<link href="https://cdn.datatables.net/1.10.18/css/jquery.dataTables.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdn.datatables.net/1.10.18/css/dataTables.bootstrap4.min.css" rel="stylesheet" />
<script src="https://cdn.datatables.net/1.10.18/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.18/js/dataTables.bootstrap4.min.js"></script>

<div class="tab-pane fade show active" id="all" role="tabpanel" aria-labelledby="all-tab">
  <div class="table-responsive overflow-x:auto;">
    <table id="allHardwareOverview" style="width:100%; float: left;" class="table table-bordered"></table>
  </div>
</div>

Upvotes: 1

Ji_in_coding
Ji_in_coding

Reputation: 1701

I can see that you are trying to order by the second column

"order": [
        [1, 'desc']
      ],

However, the 2nd column is added to your dataSet as a string, not a number, hence when you order by the second column, the data are sorted as a string, not a number.

If you make a slight adjustment to your dataSet transformation like below

//transform data set
let dataSet = results.profRigHardware.map((item, i) => [
  `<img src="${ item.smallImg }" alt="${ item.title }" height="42" width="42"> 
     <a href="${item.permalink}" target="_blank">
        ${item.title}
         </a>`,
  //`${ rentabilityHtml(parseFloat(item.daily_netProfit)) }`,
  parseFloat(item.daily_netProfit)
])

You will see that the ordering will be correct.

See the example in codepen. https://codepen.io/ji_in_coding/pen/JajXJw?editors=1010

Upvotes: 1

Related Questions