Here is a working fiddle to add row dynamically and remove if it's already there before adding.
HTML
<!-- INDEX TO ADD ON THE DATATABLE -->
<select id="recIndex">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
<option>7</option>
<option>8</option>
<option>9</option>
</select>
<!-- BUTTON TO ADD ROW -->
<input type="button" name="addRow" value="Add Row">
<!-- DATATABLE -->
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>No #</th>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
<th>Column 4</th>
<th>Column 5</th>
</tr>
</thead>
<tfoot>
<tr>
<th>No #</th>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
<th>Column 4</th>
<th>Column 5</th>
</tr>
</tfoot>
</table>
JS
In the below codes, I am checking a record is exist or not in the DataTable by checking the first TD value of each row. If the provided index counter value is in the first TD then I am assuming that already exist. And then I am adding a .remove class to remove that row. Hope you get my point.
$(document).ready(function() {
var $myTable = $('#example');
var t = $myTable.DataTable();
$('input[name="addRow"]').click(function() {
var index = $('#recIndex').val();
addRow(index);
});
function addRow(counter) {
// Check if the counter record is already exist in DataTable
// TODO: Check and provide functionality as per your requirements. Below code is done just for an example.
$myTable.find('tr').each(function() {
if($(this).find('td:first').html() == counter) {
$(this).addClass('remove'); // If you found the counter add .remove class
}
});
// Delete row by using remove class and draw
t.row('.remove').remove().draw( false );
// Add new row as per index counter
t.row.add( [
counter,
counter +'.1',
counter +'.2',
counter +'.3',
counter +'.4',
counter +'.5'
] ).draw( false );
}
} );