2017-09-25 31 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>