get the second to last item of an array?

JavascriptJqueryArrays

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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

Solution 3 - Javascript

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

Solution 4 - Javascript

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

Solution 5 - Javascript

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>

Solution 6 - Javascript

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 $()

Solution 7 - Javascript

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

Solution 8 - Javascript

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.

Solution 9 - Javascript

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.

Solution 10 - Javascript

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]

Solution 11 - Javascript

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];

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRunView Question on Stackoverflow
Solution 1 - JavascriptPablo FernandezView Answer on Stackoverflow
Solution 2 - JavascriptJJ GeewaxView Answer on Stackoverflow
Solution 3 - Javascript151291View Answer on Stackoverflow
Solution 4 - Javascriptt_dom93View Answer on Stackoverflow
Solution 5 - JavascriptPenny LiuView Answer on Stackoverflow
Solution 6 - JavascriptdaveView Answer on Stackoverflow
Solution 7 - JavascriptJason TurnageView Answer on Stackoverflow
Solution 8 - JavascriptTravis JView Answer on Stackoverflow
Solution 9 - JavascriptIpsitaView Answer on Stackoverflow
Solution 10 - JavascriptmbunchView Answer on Stackoverflow
Solution 11 - JavascriptUliana PavelkoView Answer on Stackoverflow