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.
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.
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.
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 .
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 :)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With