Winter
Winter

Reputation: 2517

lodash takeRightWhile from starting index

How do I get the values from an array using lodash's takeRightWhile with a starting index?

The point here is that I want to iterate backward from a specific starting point until a certain argument is fulfilled.

Example of what I want to do:

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

I have looked at the documentation https://lodash.com/docs/4.17.4#takeRightWhile and can't really tell if this is possible.

Is there perhaps a better way to do this?

Upvotes: 0

Views: 694

Answers (2)

Ori Drori
Ori Drori

Reputation: 191986

Lodash's _.takeRightWhile() starts from the end, and stops when a predicate is reached. The methods signature is:

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

And it doesn't accept an index.

The predication function receives the following parameters - value, index, array. The index is the position of the current item in the array.

To achieve your goal use _.take(startAt + 1) to chop the array to up to (including) the starting index, and the use _.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>

Upvotes: 1

marvel308
marvel308

Reputation: 10458

You can use slice along with lodash to do that

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>

Upvotes: 1

Related Questions