4

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.

CyberJunkie
  • 21,596
  • 59
  • 148
  • 215

1 Answers1

10

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
kev
  • 1,011
  • 8
  • 15