Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get the second to last item of an array?

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.

like image 896
Run Avatar asked Jun 27 '11 21:06

Run


People also ask

How do you return the first and last element of an array?

To get the first and last elements of an array, access the array at index 0 and the last index. For example, arr[0] returns the first element, whereas arr[arr. length - 1] returns the last element of the array.

How do I find the second last element in a list Python?

To get the last element of the list in Python, use the list[-1] syntax. The list[-n] syntax gets the nth-to-last element. So list[-1] gets the last element, and list[-2] gets the second to last.

How do you find the index of the last element?

The lastIndexOf() method returns the last index at which a given element can be found in the array, or -1 if it is not present. The array is searched backwards, starting at fromIndex .


2 Answers

Not everything has to be done using jQuery.

In plain old javascript you can do:

var pg_url = array_fragment[array_fragment.length - 2] 

Easier and faster :)

like image 185
Pablo Fernandez Avatar answered Oct 10 '22 06:10

Pablo Fernandez


Looks like you can also use Javascript's slice method:

var path = 'a/b/c/d'; path.split('/').slice(-2, -1)[0]; // c 

You can also think of "second to last element in the array" as "second element of the array reversed":

var path = 'a/b/c/d'; path.split('/').reverse()[1]; // c 
like image 44
JJ Geewax Avatar answered Oct 10 '22 06:10

JJ Geewax