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