【问题标题】:lodash takeRightWhile from starting indexlodash takeRightWhile 从起始索引
【发布时间】:2017-09-25 17:36:09
【问题描述】:

如何使用带有起始索引的 lodash 的 takeRightWhile 从数组中获取值?

这里的重点是我想从一个特定的起点向后迭代,直到满足某个参数。

我想做的例子:

const myArray = [
    {val: 'a', condition: true},
    {val: 'b', condition: false},
    {val: 'c', condition: true},
    {val: 'd', condition: true},
    {val: 'e', condition: true},
    {val: 'f', condition: true},
    {val: 'g', condition: false},
];
const startAt = 5;

const myValues = _.takeRightWhile(myArray, startAt, {return condition === true});
// --> [{val: 'c', condition: true}, {val: 'd', condition: true}, {val: 'e', condition: true}]

我查看了文档 https://lodash.com/docs/4.17.4#takeRightWhile 并不能确定这是否可行。

是否有更好的方法来做到这一点?

【问题讨论】:

    标签: javascript arrays lodash


    【解决方案1】:

    Lodash 的_.takeRightWhile() 从末尾开始,到达谓词时停止。方法签名是:

    _.takeRightWhile(array, [predicate=_.identity])
    

    而且它不接受索引。

    预测函数接收以下参数 - valueindexarrayindex 是当前项在数组中的位置。

    要实现您的目标,请使用 _.take(startAt + 1) 将数组切割到(包括)起始索引,并使用 _.takeRightWhile()

    const myArray = [{"val":"a","condition":true},{"val":"b","condition":false},{"val":"c","condition":true},{"val":"d","condition":true},{"val":"e","condition":true},{"val":"f","condition":true},{"val":"g","condition":false}];
    
    const startAt = 5;
    
    const myValues = _(myArray)
      .take(startAt + 1) // take all elements including startAt
      .takeRightWhile(({ condition }) => condition) // take from the right 'till condition is false
      .value();
    
    console.log(myValues);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

    【讨论】:

    • 谢谢!该解决方案还包括我的问题,即包括当前 (startsAt) 值。
    【解决方案2】:

    你可以使用 slice 和 lodash 来做到这一点

    const myArray = [
        {val: 'a', condition: true},
        {val: 'b', condition: false},
        {val: 'c', condition: true},
        {val: 'd', condition: true},
        {val: 'e', condition: true},
        {val: 'f', condition: true},
        {val: 'g', condition: false},
    ];
    const startAt = 5;
    
    const myValues = _.takeRightWhile(myArray.slice(0, startAt), e => e.condition == true);
    
    console.log(myValues);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>

    【讨论】:

      猜你喜欢
      • 2019-12-20
      • 2015-10-20
      • 2020-10-25
      • 1970-01-01
      • 2011-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-09
      相关资源
      最近更新 更多