84

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.

1

11 Answers 11

95

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 :)

5
  • 3
    Fail if array_fragment.length == 1
    – James
    Jun 27, 2011 at 21:30
  • 6
    @James: Fails as in "doesn't return anything", or fail as in Error? When I test it, it simply returns undefined.
    – user113716
    Jun 27, 2011 at 21:36
  • @James it does not fail actually... When you access an element that is not indexed in the array, the default behaviour is to return undefined (e.g. [1,2,3][10] === [1,2,3][-1])
    – CPHPython
    Jan 23, 2018 at 16:07
  • the problem with this approach is that you cannot chain it: 'a/b/c/d'.split('/').slice(-2, -1)[0] === 'c' May 14, 2020 at 22:08
  • Thank you @Pablo, here is an example of using this approach and avoiding undefined and negative variables. jsfiddle.net/xd5cq4rz Dec 21, 2021 at 4:05
79

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
1
  • 2
    Just a suggestion but this looks more readable: second last: path.split('/').slice(-2).reverse().pop() third last: path.split('/').slice(-3).reverse().pop() fourth last: path.split('/').slice(-4).reverse().pop() etc Mar 5, 2019 at 23:00
29

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.

It is fully supported by browsers.

Docs: Array/at

28

Step 1: Use split() Method to split the elements into an array.

var fragment_arr = fragment.split("/");

Step 2: Use slice(-2) Method to select last 2 element from array, the negative number to select from the end of an array.

var lastTwo = fragment_arr.slice(-2);

Step 3: lastTwo array contains last two elements of fragment_arr, now you can access like this

var element = lastTwo[0];
alert(element);

Short answer : you can combine step 2 and 3 like below

var element = fragment_arr.slice(-2)[0];
alert(element);
3
  • If your answer is just "try this", it is not an answer. It is a comment. To write a useful answer, please add description. Feb 12, 2016 at 9:29
  • This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - From Review Feb 12, 2016 at 9:29
  • 1
    @DanielCheung - I think, i updated what u expect and i learned how to present an answer. thank u.
    – 151291
    Feb 12, 2016 at 10:24
5

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>

2
var pg_url = array_fragment[array_fragment.length -2]

array_fragment isn't a jquery variable, it's a plain old javascript variable so no need for $()

2

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();
1

If accessing arrays in reverse is something that is going to be often required, and not just the second to last index, a simple expansion to the prototype could be used.

When extending something as large and used as the Array prototype ensure that you are not going to affect any other part of its use. This is done by making sure that the property is not enumerable so that for in will not choke anywhere else (some people and libraries use for in to iterate arrays).

Object.defineProperty(Array.prototype, 'rev', {
  enumerable: false,
  value: function(index){
    return this[this.length - 1 - index];
  }
});

document.write([1,2,3,4,5,6].rev(1));

And now you can use zero based indexing in reverse.

0
1
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.

0

The following works for a string with nth 'url' parts.

var fragment = '/t/e/s/t/i/n/g/';
var fragment = '/t/';

If the fragment is of variable length, you need a solution that works for various fragment sizes.

var fragment = '/news/article-1/';
var array_fragment = fragment.split('/');

Split separates the fragment string where it finds '/'s. Split takes the value before and after the split character. In this case there is nothing before the first slash or after the last slash. The empty values are added to the array_fragment in the first and last array positions.

jQuery
var pg_url = $(array_fragment)[$(array_fragment).length - 2];

javascript
var pg_url = array_fragment[array_fragment.length - 2];

As you can see, jQuery is not needed for this solution.

Array_fragment.length - 2 is counting the length of the array_fragment, and selecting the second item from the end. The last value is "" due to Split('/') adding an empty value to the end of the array_fragment array.

Simplified and all put together:

var f = '/t/e/s/t/i/n/g/'.split('/');
f[f.length - 2]
0
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];
1
  • JJ Geewax's answer in here already covers your answer... It's actually simpler and more detailed since it uses the second parameter of slice for the array to only have the penultimate element without declaring other variables (e.g. [1,2,3].slice(-2,-1)[0] === 2)
    – CPHPython
    Jan 23, 2018 at 15:10

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.