Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript get index of last item in an array [duplicate]

I know I can get the last item in an array using:

_.nth(arr, -1)

or arr[arr.length - 1]

or arr.slice().pop()

and many, many more...

How about getting just the index?

My array looks like this:

[
    { icon: 'twitter', url: '#'},
    { icon: 'facebook', url: '#'},
    { icon: 'instagram', url: '#'},
],

How would I get the index of the last item? I am trying to find the simplest, one line solution, without using map or looping.

Note: ReactJS solutions are also accepted if any.

like image 717
CyberJunkie Avatar asked Jan 26 '23 23:01

CyberJunkie


1 Answers

In zero-based array systems, the index of the last item in an array is always the number of items of the array minus one.

In JS, you get the number of items in an array by calling the length property of the array object.

Then you subtract one from the length of the array, because JS arrays are zero-based.

const arr = ["one", "two", "three"];    
const arrLength = arr.length;

console.log(arrLength - 1); // expected output: 2 => length of array (3) minus 1
like image 113
kev Avatar answered Jan 29 '23 13:01

kev