0

Hi i had an array with n number of objects. I want to pluck the last but one object every-time. For example i had 4 objects in an array. I want the third object to be plucked using underscore.jS. Every time i want the last but one object to be plucked out of an array.

Thanks in advance

1 Answer 1

1

You really don't need a library for this.

var ary = ['thing1', 'thing2', 'thing3', 'thing4'];

var aryLength = ary.length;

var almostLast = ary[aryLength - 2];

This works for any array, not just this example ary. It works because arrays are 0-indexed. In ary, ary[0] = 'thing1', ary[1] = 'thing2', etc. So the last thing in an array is available at the index of two less than its length.

If you need to use underscore, I guess you can use _.last() as follows:

var lastTwo    = _.last(ary, 2),
    almostLast = lastTwo[0]; 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.