How to tally the number of times a specific value occurs in a dynamically populated column.

How to tally the number of times a specific value occurs in a dynamically populated column.

GlyndwrGlyndwr Posts: 117Questions: 32Answers: 0

I am dynamically populating a column with values using:

{"data": null, //data is null since we want to access ALL data for the sake of our calculation below
                  "render": function(data,type,row) {

                      var today = new Date();
                      var t1 = today.getFullYear() + "-03-31";
                      var end = moment(t1);
                      var start = moment(data.dob);
                      var year = end.diff(start, 'years', true);

                      if(year < 8){
                          return ("J");
                      }else{
                          if(year < 11){
                              return ("C");
                          }else{
                              if(year < 14){
                                  return ("S");
                              }else{
                                  if(year < 18){
                                      return ("V");
                                  }else{
                                      if(year < 26){
                                          return ("R");
                                      }else{
                                          return ("L");
                                      }
                                  }
                              }
                          }
                      }
                  },
              },

I then want to count the number of times "J" occurs using:

var filteredData2 = cubPackDetailsTable
    .column( 8 )
    .data()
    .filter( function ( value, index ) {
        return value == "J" ? true : false;
    } ).count();
    alert("filteredData2: " + filteredData2);

This returns 0 (zero). I have also tried "=" and "===" in place of "==" which return 106 (total number of cells in the column) and 0 (zero) respectively. I have tried to create and example; however, I can not get it to work, at: live.datatables.net/fuhepave/1/edit

Kind regards,

Glyn

Answers

  • rf1234rf1234 Posts: 2,808Questions: 85Answers: 406
    edited January 2020

    You are counting it when the table has not been drawn. Depending on how often you want to see this use the "init" or "draw" event (in the docs).
    https://datatables.net/reference/event/

    Just tried this with one of my tables and the result was 1 because I have this value once in that column. Outside the event the same code produced 0.

    ctrTable
        .on ('init', function () {        i
            alert(ctrTable
                .column( 1 )
                .data()
                .filter( function ( value, index ) {
                    return value == "Stadt Oerlinghausen" ? true : false;
                } ).count())    
            });
    
This discussion has been closed.