get the second to last item of an array?

Viewed 127586

How can I get the last second item in an array?

For instance,

var fragment = '/news/article-1/'
var array_fragment = fragment.split('/');
var pg_url = $(array_fragment).last()[0];

This returns an empty value. But I want to get article-1

Thanks.

11 Answers

arr.at(-2); will do exaclty that - it returns last second item in an array.


const arr = [1,2,3,4];
arr.at(-2); // Returns 3

The at() method takes a positive or negative integer and returns the item at that index. Negative integers count back from the last item in the array.

Docs: Array/at

This can be covered by lodash _.nth:

var fragment = '/news/article-1/'
var array_fragment = _.split(fragment, '/');
var second_last = _.nth(array_fragment, -2);
console.log(second_last);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>

This question is old but still relevant. Slice with length-1 is the best bet, but as an alternative with underscore/lodash:

_.initial() gets all but the last

_.last() gets the last

So you could do

_.last(_.initial([1,2,3,4])) 

or chained:

_.chain([1,2,3,4])
 .initial()
 .last()
 .value();

which gives you back 3.

Or in the original question:

var fragment = '/news/article-1/'
var array_fragment = fragment.split('/');
var pg_url = _.chain(array_fragment).initial().last().value();
var a = [1,2,3,4];
var b = a.slice(-2,-1);
console.log(b);

The answer is [3].You just have to mention the start and end for slice.

const myArray: Array<string> = ['first', 'second', 'third'];

Split myArray by second last item.

const twoItemsFromEnd = myArray.slice(-2); //Outputs: ['second', 'third']

Then

const secondLast = twoItemsFromEnd[0];

Or:

const secondLast = (params.slice(-2))[0];
Related