corvid
corvid

Reputation: 11187

Continue chain after reduce in lodash

I want to do something like as follows

_(data)
  .map(() => /** ... */)
  .reduce(function (modifier, doc) {
    modifier.$set = modifier.$set || {};
    modifier.$set.names = doc.names;
    return modifier;
  }, {})
  .map(() => /** ... */)
  .flatten()

However, it appears that after reduce, the chain breaks.

Is there a way to continue the chain from the value returned by reduce?

Upvotes: 3

Views: 3901

Answers (2)

Mike Brant
Mike Brant

Reputation: 71384

reduce() method is not guaranteed to produce a collection (array, object, or string) upon which other methods could operate, therefore it makes no sense that it could be chainable by default.

From lodash documentation on lodash object (_):

Methods that operate on and return arrays, collections, and functions can be chained together. Methods that retrieve a single value or may return a primitive value will automatically end the chain returning the unwrapped value.

_ documentation

You can however explicitly enforce chaining by using _.chain(). This would allow for single values and primitives to be explicitly returned within lodash wrapper for continued chaining.

So for your code that might look like:

_.chain(data)
  .map(() => /** ... */)
  .reduce(function (modifier, doc) {
    modifier.$set = modifier.$set || {};
    modifier.$set.names = doc.names;
    return modifier;
  }, {})
  .map(() => /** ... */)
  .flatten()

_.chain() documentation

Upvotes: 7

Michael Rashkovsky
Michael Rashkovsky

Reputation: 156

The lodash docs say that reduce() is not chainable. See here: "The wrapper methods that are not chainable by default are: ... reduce" https://lodash.com/docs#_

Upvotes: 2

Related Questions