JavaScript get index of last item in an array

10,955

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
Share:
10,955
CyberJunkie
Author by

CyberJunkie

Updated on June 24, 2022

Comments

  • CyberJunkie
    CyberJunkie almost 2 years

    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.