Skip to content

How to get the index of an item in a JavaScript array

New Course Coming Soon:

Get Really Good at Git

Here is how to retrieve the index of an item in a JS array based on its value

Suppose you have the value of an item which is contained in an array, and you want to get its index.

How can you get it?

If the item is a primitive value, like a string or number, you can use the indexOf method of an array:

const letters = ['a', 'b', 'c']

const index = letters.indexOf('b')

//index is `1`

Remember that the index starts from the number 0

If the item is an object, you can’t use this way, because if you try doing:

const letters = [
  {
    letter: 'a',
  },
  {
    letter: 'b',
  },
  {
    letter: 'c',
  },
]

const index = letters.indexOf({
  letter: 'b',
})

index will be -1 which means the item was not found. Because objects are compared by reference, not by their values (differently for primitive types). The object passed to indexOf is a completely different object than the second item in the array.

You can use the findIndex value like this, which runs a function for each item in the array, which is passed the element, and its index. Returning from it will assign the return value to the return value of findIndex:

const letters = [
  {
    letter: 'a',
  },
  {
    letter: 'b',
  },
  {
    letter: 'c',
  },
]

const index = letters.findIndex((element, index) => {
  if (element.letter === 'b') {
    return true
  }
})

//index is `1`
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching Summer 2024. Join the waiting list!
→ Get my JavaScript Beginner's Handbook
→ Read my JavaScript Tutorials on The Valley of Code
→ Read my TypeScript Tutorial on The Valley of Code

Here is how can I help you: