Loading TOC...

TuplesSearch.reduce

TuplesSearch.reduce(
   reducer as function,
   seed as anyValue
) as TuplesSearch

Summary

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

Parameters
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:

prev
The reduced tuples returned by the previous call, or the seed value on the first call.
current
The current tuple.
index
The number of the current tuple.
state
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

Example


// 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');
jsearch.tuples(['format','price'])
  .reduce(function (accum, tuple, index, state) {
    if (!accum.hasOwnProperty(tuple[0])) {
      accum[tuple[0]] = {sum: 0, count: 0};
    }
    accum[tuple[0]].sum += tuple[1]
    accum[tuple[0]].count++;
    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()

/* 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.