JavaScript indexOf vs findIndex – [Complete Guide with Examples]

When working with arrays, you often faced a situation where you are confused about using indexOf and findIndex. This post will help you understand the findIndex and indexOf functions and what should be used in different use cases.

indexOf Array function in JavaScript

The indexOf function in JavaScript is simply used for finding the index of an element. It returns the index of an element if the element is in the array and returns -1  if the element is not in the array. In the following code snippet, you can see an example of using indexOf method on an array of numbers.

Using indexOf to Find the Character index in the String

You can also use the indexOf method to find the index of a character in a string. It will return -1 if the character is not in the string and the actual index if it is found in the string. Check the following example to see how to get the character index in a string.

This method will return the index of the first element if it is found more than once.

This indexOf the method doesn’t work with an array of objects. The following code will example prints -1 because the data is an object.

As you can see in the above example, indexOf doesn’t work with an array of objects. It only works with numbers or strings. So, if you have an array of objects, you need to use the other method indexOf.

Using indexOf method to Find the Index of an Object

When working with an array of objects you might need to find the index of an object. The method indexOf is very useful in those situations. The indexOf method expects a callback function as a parameter and you need to specify a condition. The following example explains how to use indexOf method to get the index of an Object.

You can read more about finding the index of an object in an array and also check the indexOf and findIndex methods in detail.

Conclusion

JavaScript array methods indexOf and findIndex are used to find the element index in an array. The indexOf method only works with numbers or string arrays and doesn’t work with an array of objects. The method findIndex is used to get the index of an object from an array of objects.

Latest articles

Related articles