简体   繁体   中英

Filter, reduce, map with lodash _.flow

As a beginner applying the lodash library in the functional programming, I found that ._flow doesn't excute the functions put in. My question is how do I apply map, reduce, or filter inside the flow? Or anything that I did wrong? Any help is highly appreciated.

For example:

const _=require('lodash');
const scores = [50, 6, 100, 0, 10, 75, 8, 60, 90, 80, 0, 30, 110];

const newArray=_.filter(scores,val=>val<=100);
const newArray2=_.filter(newArray,val=>val>0);
console.log(newArray2);

// the output is
 /*[
  50,  6, 100, 10, 75,
   8, 60,  90, 80, 30
]*/

However, when I make it two separate functions and put into flows, it doesn't do anything.

const newRmvOverScores=_.filter(val=>val<=100);
const newRmvZeroScores=_.filter(val=>val>0);
const aboveZeroLess100=_.flow(newRmvOverScores,newRmvZeroScores)(scores);

console.log(aboveZeroLess100);

// the output is:
 /*[
   50,  6, 100,  0, 10, 75,
    8, 60,  90, 80,  0, 30,
  110
]*/

Several references I've found:

[1] Using lodash, why is the map method within flow not working? [2] https://lodash.com/docs/4.17.15#flow

Two issues:

  • When defining newRmvOverScores and newRmvZeroScores , you actually already execute _.filter , and without a collection argument. They should be functions
  • _.flow expects an array of functions, but you don't provide an array, nor are the arguments functions (because of the previous point)

Here is the corrected script:

 const scores = [50, 6, 100, 0, 10, 75, 8, 60, 90, 80, 0, 30, 110]; const newRmvOverScores = scores => _.filter(scores, val=>val<=100); const newRmvZeroScores = scores => _.filter(scores, val=>val>0); const aboveZeroLess100 = _.flow([newRmvOverScores,newRmvZeroScores])(scores); console.log(aboveZeroLess100);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"></script>

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