简体   繁体   中英

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 ?

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM