A very common operation we perform when coding, is trying to determine if an element or item exists in an array.

This can be simple, such as determining if the number 5 exists in an array of integers, or trying to find out if the string "Hello" exists in an array of strings. Slightly more complicated is determining if an object is in an array, which is usually accomplished in a simple manner by having some unique key that identifies each object.

When it comes to searching through an array, not all techniques are the same. And in this particular situation, the order of the array can affect how quickly we can find an item.

Finding An Item In An Unsorted Array

If we need to find an item in an unsorted array there really are not many other options, we have to look at every item. There is no magic way to know without looking at every item. In Javascript, we can accomplish this in many different ways. See below for a few different implementations.

const someData = [2,8,5,4,7,3]

// Loop through all Items and see if we find the item
// Either item is returned or null is returned
const findItem = (find, items) => {
  let found = null;
  for(const item of items){
    if(item === find){
      found = item;
      break;

You can see there are actually many ways, and there are others that could be derived which are not pictured here. These are the most common ways that you can find an item in an array. Overall, all of these result in linear runtime complexity (O(N)), and there is no real improvement on that unless we have a sorted array. We will visit this situation next.

#interview #coding #programming #javascript

Several Ways to Find an Item in an Array in JavaScript
1.05 GEEK