Zarul Zakuan
Zarul Zakuan

Reputation: 520

Limit number of data in table

I connected my datatables with websocket to display live data from backend. The data is live feed so the row is added continuously.

Question: How do I make datatables to remove the old data when it reaches for example 1000 rows, so in one table only 1000 rows are displayed?

Upvotes: 0

Views: 1728

Answers (1)

user3307073
user3307073

Reputation:

You may listen for preDraw event which is fired exactly before you redraw datatable as you pushed new data in. So, you may check whether the row count is exceeded and find and remove oldest entry.

That might work, I guess:

//define initial data sample
const srcData = [{parameter: 'CPU usage, %', value: Math.floor(Math.random()*100), timestamp: (new Date()).toString()}];
//define datatable object
const dataTable = $('#mytable').DataTable({
  sDom: 't',
  data: srcData,
  columns: [
    {title: 'parameter', data: 'parameter'},
    {title: 'value', data: 'value'},
    {title: 'timestamp', data: 'timestamp'}
  ]
});
//emulate new data insertion
const dataPooler = window.setInterval(function(){
	dataTable.row.add({parameter: 'CPU usage, %', value: Math.floor(Math.random()*100), timestamp: (new Date()).toString()}).draw();
},3000);
//listen for new draws, purge oldest entry
dataTable.on('preDraw', function(){
	if(dataTable.rows().count() < 5) return;
  //grab the oldest entry timestamp
	let oldestTimestamp = dataTable.column(2).data().toArray().map(entry => new Date(entry)).sort()[0].toString();
	//look through the table and purge corresponding entry if table has more than 10 entries
	let oldestEntryIndex = dataTable.column(2).data().indexOf(oldestTimestamp)
	dataTable.row(oldestEntryIndex).remove();
});
<!doctype html>
<html>
  <head>
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
    <script type="application/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    <script type="application/javascript" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
  </head>
  <body>
    <table id="mytable"></table>
  </body>
</html>

Upvotes: 3

Related Questions