get a count of records matching a value

get a count of records matching a value

getalexgetalex Posts: 39Questions: 11Answers: 1

I have a table that should have a unique column value for each row. I want to prevent new data entry if a row exists with this unique key value already.. my thought was i could validate on submit, something like this:

// second column should be unique
var total = dt.columns(1).search( newRowKeyToFind ).count();
if (total > 0) return false or alert of issue ...

I read the API says search won't actually execute until the draw() method is called, so I tried using the Filter API, but can't get the value to match or find any examples on usage for the scenario I illustrated above.

Can somebody please help with some simple code for this?

Answers

  • getalexgetalex Posts: 39Questions: 11Answers: 1

    This is the best I could come up with, please let me know if there's a better way:

    var valueToFind = "peanuts";
    
    var duplicateCheck = dt.columns(1).data().filter(function (value, index) {
            var foundDuplicate = false;
            for (i = 0; i < value.length; i++) {
                if (value[i] === valueToFind) {
                    foundDuplicate = true;
                    break;
                }
            }
            return foundDuplicate;
        }).count();
    
  • kthorngrenkthorngren Posts: 20,302Questions: 26Answers: 4,769
    edited October 2018

    Maybe something like this?

    var valueToFind = "peanuts";
     
    var duplicateCheck = dt.columns(1).data().filter(function (value, index) {
            return value ===  valueToFind ? true : false;
        }).length;
    

    duplicateCheck should equal 0 if peanuts is not in the data or will equal the number of found results. This is based on the example code in the filter() docs.

    Kevin

This discussion has been closed.