Loading TOC...


   reducer as function,
   seed as anyValue
) as TuplesSearch


Specifies a function similar to Array.prototype.reduce() to apply to each tuple within the slice.

reducer The reducing function.
seed The initial reduction passed to the reducing function.

Usage Notes

The reducer function should have the following signature:

function (prev, current, index, state)

Where the parameters have the contents:

The reduced tuples returned by the previous call, or the seed value on the first call.
The current tuple.
The number of the current tuple.
A state object with a boolean-valued isLast> property that indicated the last call. You can set it to true to prematurely halt the reduction.

The return from the last call becomes the final reduced result.

You cannot use this method in conjunction with TuplesSearch.map.

See Also


// A custom reducer that computes the average price of each format.
// The reduction is initially seeded with an empty object for the
// accumulator. 
const jsearch = require('/MarkLogic/jsearch.sjs');
  .reduce(function (accum, tuple, index, state) {
    if (!accum.hasOwnProperty(tuple[0])) {
      accum[tuple[0]] = {sum: 0, count: 0};
    accum[tuple[0]].sum += tuple[1]
    if (state.isLast) {
      const result = {};
      for (let k in accum) {
        if (accum.hasOwnProperty(k)) {
          result[k] = accum[k].sum / accum[k].count;
      return result;
    } else {
      return accum;
  }, {})

/* Result: Assuming the values in the 'format' index are "audiobook",
    "hardback", and "paperback", the output is similar to the following:

{"audiobook":16, "hardback":19, "paperback":14.25}

Stack Overflow iconStack Overflow: Get the most useful answers to questions from the MarkLogic community, or ask your own question.