如何使用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并且无法确定这是否可行。
是否有更好的方法可以做到这一点?
答案 0 :(得分:1)
Lodash的_.takeRightWhile()
从结尾开始,到达谓词时停止。方法签名是:
_.takeRightWhile(array, [predicate=_.identity])
它并不接受索引。
预测功能会收到以下参数 - value
,index
,array
。 index
是数组中当前项的位置。
要实现您的目标,请使用_.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>
&#13;
答案 1 :(得分:1)
您可以将切片与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);
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
&#13;