array index
find index
search array
value in array
programming tutorial

Find array index if given value

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Finding the index of a value in an array or list is a basic operation, but the right approach depends on whether you want the first match, all matches, or fast lookups on repeated searches. The main technical issues are handling missing values, duplicates, and algorithmic cost. A linear scan is simple and correct for most cases, but there are better choices for sorted or repeatedly queried data.

First Match in Common Languages

Most languages provide a built-in way to find the first matching position. These APIs usually return the first index and a sentinel value such as -1 or raise an error if nothing is found.

python
1values = ["red", "blue", "green", "blue"]
2
3first_blue = values.index("blue")
4print(first_blue)  # 1
5
6try:
7    print(values.index("black"))
8except ValueError:
9    print("not found")

Python raises ValueError for a missing element, so you often wrap the call in try and except when absence is expected.

javascript
1const values = ["red", "blue", "green", "blue"];
2
3console.log(values.indexOf("blue"));   // 1
4console.log(values.indexOf("black"));  // -1

JavaScript returns -1, which makes a direct comparison easy before using the index.

Writing the Search Explicitly

A manual loop is useful when you need custom matching rules, such as case-insensitive comparison or matching part of an object.

python
1def find_index(items, target):
2    for i, item in enumerate(items):
3        if item == target:
4            return i
5    return -1
6
7print(find_index([10, 20, 30], 20))
8print(find_index([10, 20, 30], 99))

This version is also a good teaching tool because it makes the algorithm obvious: inspect each element from left to right and stop at the first match.

Handling Duplicates

If the same value appears multiple times, a standard index call only gives the first position. Sometimes that is exactly what you want. Other times you need every index.

python
items = ["a", "b", "a", "c", "a"]
positions = [i for i, value in enumerate(items) if value == "a"]
print(positions)  # [0, 2, 4]

That pattern is simple and avoids repeated list.index() calls, which can be inefficient and error-prone when duplicates are involved.

In JavaScript:

javascript
1const items = ["a", "b", "a", "c", "a"];
2const positions = items
3  .map((value, index) => value === "a" ? index : -1)
4  .filter(index => index !== -1);
5
6console.log(positions);

Searching Objects Instead of Primitive Values

Real arrays often contain records rather than numbers or strings. In that case, search by a property.

javascript
1const users = [
2  { id: 10, name: "Ava" },
3  { id: 11, name: "Noah" },
4  { id: 12, name: "Mia" }
5];
6
7const idx = users.findIndex(user => user.id === 11);
8console.log(idx);  // 1

findIndex is clearer than manually looping when the match condition is a predicate.

Performance Considerations

A normal index lookup on an unsorted array is O(n) because the program may need to inspect every element. That is fine for one-off lookups on small or medium arrays. It becomes less attractive when:

  • the array is very large
  • you perform many searches
  • the array is sorted and can support faster search

For sorted data, binary search reduces lookup time to O(log n).

python
1import bisect
2
3values = [3, 8, 12, 20, 25]
4target = 12
5
6pos = bisect.bisect_left(values, target)
7if pos < len(values) and values[pos] == target:
8    print(pos)
9else:
10    print("not found")

For repeated lookups by value, a dictionary or hash map is usually better than scanning the same array over and over.

python
1values = ["red", "blue", "green"]
2index_by_value = {value: i for i, value in enumerate(values)}
3
4print(index_by_value.get("green"))  # 2
5print(index_by_value.get("black"))  # None

This works best when values are unique. If duplicates matter, store lists of positions instead of a single index.

Choosing the Right Return Contract

One design choice matters more than it first appears: what should the function return when the value is missing. Common choices are -1, None, null, or an exception. The right answer depends on the language and the calling style. Exceptions work well when absence is unexpected. Sentinel values are easier when missing data is part of normal control flow.

Try to keep the contract consistent across your codebase. Mixing -1 in one helper and None in another leads to avoidable bugs.

Common Pitfalls

The most common mistake is assuming the built-in lookup returns all matches when it usually returns only the first one. Another frequent bug is forgetting to handle the not-found case before indexing into the array. Developers also sometimes use repeated linear scans inside loops, which can quietly turn a simple task into quadratic work. If the data is sorted, not taking advantage of binary search is another missed optimization.

Summary

  • Use the language built-in such as index, indexOf, or findIndex for simple first-match searches.
  • Use a manual loop or predicate-based search when you need custom matching logic.
  • Collect indices explicitly if duplicates matter.
  • Handle missing values deliberately with a clear return contract.
  • Switch to binary search or a hash map when repeated lookups or large datasets make linear scans too expensive.

Course illustration
Course illustration

All Rights Reserved.