Search code examples
javascriptlodashchain

How to get collection in a lodash chain?


I am currently using lodash with chain. I did something like that :

let result = _(myCollection)
    .filter(...)
    .map(...)
    .value()
return _.reduce(result, (a, b) => a && b, result.length != 0)

But I am not happy with that. I would like to do all in one instruction in order to obtain something like that :

return _(myCollection)
    .filter(...)
    .map(...)
    .reduce((a, b) => a && b, myMappedCollection.length != 0)
    .value()

I can't find a way to get back my collection currently processed. Is there a way to do that ?


Solution

  • As specified in the documentation: https://lodash.com/docs/4.17.4#reduce

    Reduces collection to a value which is the accumulated result of running each element in collection thru iteratee, where each successive invocation is supplied the return value of the previous. If accumulator is not given, the first element of collection is used as the initial value. The iteratee is invoked with four arguments: (accumulator, value, index|key, collection).

    You could do the following

    return _(myCollection)
    .filter(...)
    .map(...)
    .reduce((a, b, indx, myMappedCollection) => a && b, myMappedCollection.length != 0)
    .value()