2017-09-25 1 views
0

Wie bekomme ich die Werte von einem Array mit lodash TakeRightWhile mit einem Startindex?lodash TakeRightWhile vom Startindex

Der Punkt hier ist, dass ich von einem bestimmten Startpunkt rückwärts iterieren will, bis ein bestimmtes Argument erfüllt ist.

Beispiel von dem, was ich tun möchte:

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}] 

Ich habe in der Dokumentation https://lodash.com/docs/4.17.4#takeRightWhile geschaut und kann nicht wirklich sagen, ob dies möglich ist.

Gibt es vielleicht einen besseren Weg, dies zu tun?

Antwort

1

Lodashs _.takeRightWhile() beginnt am Ende und endet, wenn ein Prädikat erreicht ist. Die Methodensignatur lautet:

Und es akzeptiert keinen Index.

Die Prädikationsfunktion empfängt die folgenden Parameter - value, index, array. Die index ist die Position des aktuellen Elements im Array.

Um Ihr Ziel zu erreichen _.take(startAt + 1) verwendet das Array zu hacken, um bis zu (einschließlich) den Startindex und die Verwendung _.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

Danke! Diese Lösung beinhaltete mein Problem, den aktuellen Wert (startsAt) mit einzubeziehen. – Winter

1

Sie Scheibe zusammen mit lodash verwenden können, um tun, dass

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>