reduce()
Apply a callback function against and accumulator and each element in the Api's result set (left-to-right).
Description
This method can be used to accumulate data from a result set into a single value. A good example is summing the values from a column of data. A more complete definition of the Array reduce method, which this method is based upon, can be found on the Mozilla MDN documentation for reduce
.
Note that the traversal of the elements in the result set in this method is left-to-right (i.e. 0 to length
). reduceRight()
is available for transversal in the opposite direction.
This method makes use of the fact that DataTables API objects are "array like", in that they inherit a lot of the abilities and methods of the Javascript Array
type.
In this case, this method is a proxy for the Javascript Array.prototype.reduce
method and is provided as a utility method for the DataTables API. For more information about the original method, please refer to the Mozilla MDN documentation for reduce
. In browsers which do not support reduce
natively, a polyfill is provided to allow this DataTables method to operate as expected.
Type
function reduce( fn [, initialValue ] )
- Description:
Apply a callback function against and accumulator and each element in the Api's result set.
- Parameters:
Name Type Optional 1 fn
No Callback function which is called for each item in the API instance result set. The callback is called with four parameters:
- Current accumulator value, or
initialValue
if supplied in the first callback - Current element value
- The element index in the result set
- The API instance being traversed
The callback should return the value to be used as the accumulator for the next loop (first parameter in the callback).
2 initialValue
Any
Yes - default: Value to use as the first argument of the first call to the
fn
callback.- Current accumulator value, or
- Returns:
Any
Result from the final call to the
fn
callback function.
Example
Sum the data in a column:
var table = new DataTable('#myTable');
var sum = table
.column(0)
.data()
.reduce(function (a, b) {
return a + b;
});