Range Filter: Reduce of empty array with no initial value

Range Filter: Reduce of empty array with no initial value

mcarlottamcarlotta Posts: 11Questions: 4Answers: 0
edited January 2015 in DataTables 1.10

I have added the range_filter plugin to my DataTable

$.fn.dataTable.ext.search.push(
    function( settings, data, dataIndex ) {
        var min = parseInt( $('#min').val(), 10 );
        var max = parseInt( $('#max').val(), 10 );
        var ooh = parseInt( data[7] ) || 0; // use data for the ooh column
 
        if ( ( isNaN( min ) && isNaN( max ) ) ||
             ( isNaN( min ) && ooh <= max ) ||
             ( min <= ooh   && isNaN( max ) ) ||
             ( min <= ooh   && ooh <= max ) )
        {
            return true;
        }
        return false;
    }
);

However, when I filter, I see this in the console:

Uncaught TypeError: Reduce of empty array with no initial value

How do I address this issue?

Update: Console is finding an error in my summation code where ".reduce" is when i place a value inside the "min" "max" filters

// Total DEC over current page
            if (api.column( 6 ).data().length){
                var decTotal = api
                    .column( 6, { page: 'current'} )
                    .data()
                    .reduce( function (a, b) {
                        return intVal(a) + intVal(b);
                    } ) }
                else{ decTotal = 0};

Answers

  • allanallan Posts: 61,744Questions: 1Answers: 10,111 Site admin

    Hi,

    The error you are seeing isn't actually due to the range filter (at least not directly) but rather the use of reduce(). If the table has no data displayed in it for whatever reason (most likely the filter in this case!), then reduce() is throwing an error on the empty data set.

    The if condition isn't working because it isn't checking the same thing as what is used in the following block (note that line 4 uses {page: 'current'} while line 2 doesn't).

    The way to address this is to give reduce() an initial value in its second parameter - so your code would become:

                    var decTotal = api
                        .column( 6, { page: 'current'} )
                        .data()
                        .reduce( function (a, b) {
                            return intVal(a) + intVal(b);
                        }, 0 );
    

    You don't need to worry about checking for a data length since the initial value will simply be used if there is no data!

    Regards,
    Allan

This discussion has been closed.