array
element
check
programming
tutorial

How to check if an element is in an array

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

In programming, arrays are ubiquitous data structures that hold multiple elements, typically of the same data type, in a fixed-size sequence. One common operation when working with arrays is checking whether a particular element exists within it. This operation is crucial for tasks such as searching, filtering, and validating data. This article explores various methods to determine if an element is in an array, focusing on several popular programming languages.

Basic Concept

The fundamental approach to checking if an element is in an array involves iterating over the array and comparing each element with the target element. If a match is found, the search ends. In most programming languages, this can be implemented in a straightforward manner, but many languages also offer built-in functions to simplify this process.

Detailed Examination per Programming Language

JavaScript

In JavaScript, the Array.prototype.includes() method provides a direct way to test for the presence of an element:

javascript
1const array = [1, 2, 3, 4, 5];
2const element = 3;
3
4const hasElement = array.includes(element); // true

Alternatively, the Array.prototype.indexOf() method can be used, which returns the index of the element if found, or -1 if not:

javascript
const index = array.indexOf(element);
const hasElement = index !== -1; // true

Python

Python offers the in keyword, which is both efficient and easy to read:

python
1array = [1, 2, 3, 4, 5]
2element = 3
3
4has_element = element in array  # True

For scenarios demanding more control, the use of list.index() can also be useful:

python
1try:
2    index = array.index(element)
3    has_element = True
4except ValueError:
5    has_element = False

Java

Java doesn't provide a direct method for primitive arrays, but for object arrays, Arrays.asList(array).contains(element) can be used. For primitive arrays, a simple loop or streams API is necessary:

java
1int[] array = {1, 2, 3, 4, 5};
2int element = 3;
3boolean hasElement = false;
4
5for (int num : array) {
6    if (num == element) {
7        hasElement = true;
8        break;
9    }
10}

Alternatively, for object arrays:

java
String[] array = {"a", "b", "c"};
boolean hasElement = Arrays.asList(array).contains("b"); // true

C++

While C++ does not have built-in support like some higher-level languages, using the std::find algorithm from the Standard Library offers an efficient solution:

cpp
1#include <algorithm>
2#include <vector>
3
4std::vector<int> array = {1, 2, 3, 4, 5};
5int element = 3;
6
7bool hasElement = std::find(array.begin(), array.end(), element) != array.end(); // true

Best Practices

  1. Use Built-in Functions: When available, using built-in functions like includes, in, or similar simplifies code and often optimizes performance.
  2. Consider Time Complexity: Typically, a search in an unsorted list has a time complexity of O(n)O(n), where nn is the number of elements. Sorting the list first and using binary search reduces this to O(logn)O(\log n) for the search, but introduces additional complexity for sorting.
  3. Handle Nulls and Undefined Values: Be mindful of how the language handles null, undefined, or similar constructs, as they may affect your logic.
  4. Check for Multiple Occurrences: Determine whether you only need to check for existence or count occurrences, as this will affect your implementation.

Key Points Summary

LanguageMethodAdditional Notes
JavaScriptarray.includes(element) array.indexOf(element)Fast and native to ECMAScript indexOf returns -1 if not found
Pythonelement in array array.index(element)in is Pythonic and clear index throws exception if not found
JavaArrays.asList(array).contains(element) Loop methodNo direct method for primitives Streams can be utilized
C++std::find(array.begin(), array.end(), element)Requires #include <algorithm> Efficiency tied to iterator types

Conclusion

Determining if an element is within an array is a fundamental programming operation, with various language-specific approaches offering efficiency and readability. By leveraging built-in functions and thoughtful algorithm selection, developers can ensure their solutions are both performant and elegant.


Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.