首页 > 解决方案 > 使用 lodash _.flow 过滤、减少、映射

问题描述

作为一个在函数式编程中应用lodash库的初学者,我发现它._flow并没有执行放入的函数。我的问题是如何在流中应用map、reduce或filter?还是我做错了什么?非常感谢任何帮助。

例如:

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

但是,当我将它设为两个独立的函数并放入流时,它什么也没做。

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

我找到了几个参考资料:

[1]使用 lodash,为什么 flow 中的 map 方法不起作用? [2] https://lodash.com/docs/4.17.15#flow

标签: javascriptfunctional-programminglodash

解决方案


两个问题:

  • 定义newRmvOverScoresand时newRmvZeroScores,您实际上已经执行 _.filter了 , 并且没有集合参数。它们应该是函数
  • _.flow需要一个函数数组,但您不提供数组,参数函数也没有(因为上一点)

这是更正后的脚本:

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>


推荐阅读