2017-09-25 16 views
0

시작 인덱스가있는 lodash의 takeRightWhile을 사용하여 배열에서 값을 가져 오는 방법은 무엇입니까?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 살펴 보았다이 가능한 경우 정말 말할 수 없다.

아마도 더 좋은 방법이 있을까요?

답변

1

Lodash의 _.takeRightWhile()은 끝에서부터 시작하여 술어에 도달하면 중지됩니다. 메소드 서명은 다음과 같습니다.

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

그리고 색인을 허용하지 않습니다.

예측 함수는 value, index, array을 수신합니다. index은 배열의 현재 항목 위치입니다.

은 당신의 목표에 배열을 잘게 _.take(startAt + 1)을 사용하여 달성하기까지 (포함) 시작 인덱스 및 사용 _.takeRightWhile()에 : 당신은에 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 = _(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

어떻게 그

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>