Ship internal tools in hours, not weeks. Real auth, users, jobs, audit logs, and cohesive UI included. Early access $249 $499 → [Get it now]

How to find the index of an element in an array in JavaScript

Finding the index position of elements in arrays is essential for data manipulation, conditional logic, and implementing features like highlighting, sorting, or removing specific items in JavaScript applications. With over 25 years of experience in software development and as the creator of CoreUI, I’ve implemented index searching extensively in components like sortable lists, selection systems, and data tables where precise element positioning is crucial. From my extensive expertise, the most straightforward and efficient solution is using the indexOf() method for primitive values, which returns the first occurrence’s index. This approach is fast, widely supported, and specifically designed for finding element positions.

Use the indexOf() method to find the index position of an element in an array.

const fruits = ['apple', 'banana', 'orange', 'banana']
const index = fruits.indexOf('banana')
// Result: 1

The indexOf() method searches the array from the beginning and returns the index of the first occurrence of the specified element, or -1 if the element is not found. In this example, fruits.indexOf('banana') returns 1 because 'banana' first appears at index 1. The method uses strict equality (===) for comparison, so it works reliably with strings, numbers, and booleans.

1. Finding the Index of Primitive Values

The indexOf() method is ideal for arrays containing strings, numbers, or booleans. It performs a simple strict equality check against each element.

const scores = [10, 25, 50, 75, 100]
const position = scores.indexOf(50)
// Result: 2

const missing = scores.indexOf(99)
// Result: -1 (not found)

When the element is not found, indexOf() returns -1. You should always check for this value before using the result as an actual index to avoid off-by-one errors or accessing undefined elements. This pattern is common in CoreUI Navigation components where you need to determine the active tab position.

2. Searching from a Specific Index

The indexOf() method accepts an optional second argument, fromIndex, which specifies where to begin the search. This is useful when you know an element appears multiple times and want to skip past earlier occurrences.

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

// Find first 'b'
const first = letters.indexOf('b')
// Result: 1

// Find next 'b' after position 1
const second = letters.indexOf('b', first + 1)
// Result: 3

// Find next 'b' after position 3
const third = letters.indexOf('b', second + 1)
// Result: 5

By passing first + 1 as the starting index, the search skips the already-found occurrence and continues forward. This technique is helpful for building search-and-replace features or iterating through all positions of a repeating value.

3. Finding the Last Occurrence with lastIndexOf()

When you need the position of the last occurrence rather than the first, use lastIndexOf(). It searches the array from end to start.

const tags = ['react', 'vue', 'angular', 'react', 'svelte']

const lastReact = tags.lastIndexOf('react')
// Result: 3

const lastEmber = tags.lastIndexOf('ember')
// Result: -1

lastIndexOf() is particularly useful in CoreUI Breadcrumb components or navigation trails where you need to find the most recent occurrence of a path segment. Like indexOf(), it also accepts an optional fromIndex parameter to limit the search range.

4. Finding the Index of Objects with findIndex()

The indexOf() method uses strict equality, which means it cannot match objects by their properties — two objects with the same content are different references. For arrays of objects, use findIndex() with a callback function.

const users = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
  { id: 3, name: 'Charlie' }
]

const bobIndex = users.findIndex(user => user.id === 2)
// Result: 1

const unknownIndex = users.findIndex(user => user.id === 99)
// Result: -1

The findIndex() method executes the callback for each element and returns the index of the first element where the callback returns true. This is the go-to method when working with data fetched from APIs, such as rows in a CoreUI Smart Table where you need to locate a specific record by its ID.

5. Handling the NaN Edge Case

A subtle pitfall: indexOf() cannot find NaN in an array because NaN !== NaN in JavaScript. Use findIndex() with Number.isNaN() to handle this edge case.

const values = [1, NaN, 3, 4]

// indexOf fails for NaN
const wrongIndex = values.indexOf(NaN)
// Result: -1 (not found, even though NaN is at index 1)

// findIndex with Number.isNaN works correctly
const correctIndex = values.findIndex(Number.isNaN)
// Result: 1

This is an important distinction when processing numeric datasets that may contain invalid or missing values. Number.isNaN() is the only reliable way to test for NaN equality in JavaScript.

6. Handling Missing Elements Safely

Before using a found index to access or manipulate an array, always verify that the element was actually found. Using -1 as an index leads to undefined values or unexpected behavior.

const colors = ['red', 'green', 'blue']
const index = colors.indexOf('yellow')

// Bad: using index without checking
// colors[index] would be undefined

// Good: check before using
if (index !== -1) {
  console.log(`Found at position ${index}`)
  colors.splice(index, 1)
} else {
  console.log('Element not found')
}

This defensive pattern is essential in production applications. In CoreUI List Group components, we use this exact approach when toggling active states — verifying the item exists before modifying the selection array. For more on removing elements, see how to remove a specific item from an array.

7. Finding Multiple Indices

Sometimes you need all positions of a value, not just the first or last. You can combine indexOf() with a loop to collect every occurrence.

const data = [5, 3, 8, 3, 1, 3, 9]

const findAllIndices = (arr, value) => {
  const indices = []
  let idx = arr.indexOf(value)
  
  while (idx !== -1) {
    indices.push(idx)
    idx = arr.indexOf(value, idx + 1)
  }
  
  return indices
}

const allThrees = findAllIndices(data, 3)
// Result: [1, 3, 5]

This utility function starts from the first occurrence and keeps searching forward until indexOf() returns -1. It’s a clean pattern for building highlight or search features where every match needs to be marked.

Best Practice Note:

This is the same approach we use in CoreUI components for managing active states and element positioning in navigation systems. Use indexOf() for primitives, findIndex() for objects and complex conditions, and lastIndexOf() for reverse searches. Always check if the returned index is not -1 before using it. For related operations, see how to check if an array contains a value, how to remove a specific item, and how to get the first element.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.

Answers by CoreUI Core Team