Duplicate data in the data table

Duplicate data in the data table

vineela374vineela374 Posts: 17Questions: 8Answers: 0

I am adding data from one table to another table. I want to check if there is any in built function which checks for duplicates before adding to the data table. I do have a primary key.

This question has an accepted answers - jump to answer

Answers

  • colincolin Posts: 15,146Questions: 1Answers: 2,586

    No, DataTables doesn't restrict what you add to the table. You could check yourself fairly easily with something like table.column(pk_column).data().toArray().indexOf(pk) !== -1,

    Colin

  • vineela374vineela374 Posts: 17Questions: 8Answers: 0
        var jsonRow = {
          
            "id": data.id,
            "status": data.status,
            "title": data.title
    
        };
    PlayListTable.row.add(jsonRow).draw();
    
    

    If this is how I am adding to the data to the table, how should I check if the existing table already has id or not?

  • kthorngrenkthorngren Posts: 20,309Questions: 26Answers: 4,770

    The code that Colin provided should work. Did you try it?

    Might look something like this:

    var jsonRow = {
           
        "id": data.id,
        "status": data.status,
        "title": data.title
     
    };
    
    pk_column = 0; // ID column
    pk = jsonRow.id
    
    if ( PlayListTable.column(pk_column).data().toArray().indexOf(pk) !== -1 )  {
      PlayListTable.row.add(jsonRow).draw();
    }
    

    Kevin

  • vineela374vineela374 Posts: 17Questions: 8Answers: 0

    Yeah, I tried.. it did not work..

    pk_column = 0; // ID column
    
    

    What is this pk_column?? Can you explain?

  • kthorngrenkthorngren Posts: 20,309Questions: 26Answers: 4,770
    edited December 2019 Answer ✓

    Which table column contains "id": data.id,? I made an assumption it is 0 (the first column). You may want to look the column() column-selector docs to see how to select the appropriate column.

    When you say it doesn't work what happens? Do you get console errors? Does the row get added when the ID is already there?

    Maybe you can post a link to your page are a test case so we can see exactly what you are doing. This will allow us to more easily help you debug your code.
    https://datatables.net/manual/tech-notes/10#How-to-provide-a-test-case

    Kevin

  • vineela374vineela374 Posts: 17Questions: 8Answers: 0

    This is never adding the row because the value is always === -1

    if ( PlayListTable.column(pk_column).data().toArray().indexOf(pk) !== -1 ){
    }
    

    instead this is working in my case

    if ( PlayListTable.column(pk_column).data().toArray().indexOf(pk) === -1 ){
    }
    

    The second one is not letting me add any duplicates to the table at all.

This discussion has been closed.