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

By

Learn how to find the index of an item in a JavaScript array, using indexOf for primitive values and findIndex with a callback for objects.

~~~

To get the index of an item in an array, use indexOf() if the item is a primitive value, like a string or a number. If the item is an object, use findIndex() with a callback instead.

Let’s see both, and why you need two different methods.

Finding primitive values with indexOf()

If the item is a primitive value, 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 value is not in the array, indexOf() returns -1. Always check for it before using the index:

const index = letters.indexOf('z')

if (index === -1) {
  console.log('not found')
}

Two more things worth knowing. You can pass a second argument to start searching from a given position. And if the value appears more than once, indexOf() returns the first occurrence. Use lastIndexOf() to get the last one.

Why doesn’t indexOf() work with objects?

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.

That’s because objects are compared by reference, not by their values (differently from primitive types). The object we passed to indexOf looks identical to the second item in the array, but it’s a completely different object in memory. So the comparison fails.

Finding objects with findIndex()

For objects, use findIndex(). It runs a function for each item in the array, and returns the index of the first item for which the function returns true:

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

//index is `1`

You decide what “equal” means, by comparing the properties you care about.

Like indexOf(), findIndex() returns -1 when no item matches.

Watch out for NaN

Here’s one edge case. indexOf() uses strict equality, and NaN is never equal to itself, so you can’t find it this way:

const values = [2, NaN, 8]

values.indexOf(NaN) //-1

If you need the index of NaN, use findIndex() with Number.isNaN():

values.findIndex(Number.isNaN) //1
~~~

Related posts about js: