Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery get next to last item from data() array [duplicate]

I have an array stored in data()

$('body').data('my-array', [red, blue, orange, green]);

What is the quickest way to get the penultimate item from the array? In this case orange.

I tried:

$('body').data('my-array').get(-2);

and get $(...).data(...).get is not a function.

Note: I found similar questions but not related to arrays from data(). Please check before marking as duplicate.

like image 720
CyberJunkie Avatar asked Feb 21 '26 18:02

CyberJunkie


1 Answers

Access it like a regular array, which is what it is, and use the length and subtract from it to get the second to last value

var arr  = $('body').data('my-array');

var item = arr[arr.length - 2];

jQuery's data() stores objects and arrays as what they are, there's no magic, and when getting the data back it's accessible like any other object or array.

Note that length starts at 1, and arrays are zero-indexed, so you have to subtract 2.

like image 195
adeneo Avatar answered Feb 23 '26 06:02

adeneo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!