2017-09-25 55 views
0

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

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

例子:

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并不能真正告诉我们,如果这是可能的。

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

回答

1

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

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

而且它不接受索引。

预测函数接收以下参数 - valueindex,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>

+0

谢谢!这个解决方案还包括了我的包含当前(startsAt)值的问题。 – Winter

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);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>