gpt4 book ai didi

javascript - lodash takeRightWhile 从起始索引开始

转载 作者:行者123 更新时间:2023-12-01 03:01:22 25 4
gpt4 key购买 nike

如何使用 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并且无法真正判断这是否可能。

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

最佳答案

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

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

并且它不接受索引。

预测函数接收以下参数 - value , index , arrayindex是数组中当前项的位置。

要实现您的目标,请使用 _.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>

关于javascript - lodash takeRightWhile 从起始索引开始,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46411013/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com