Hey there! Welcome to Hostman! 🎉

Methods to Search Arrays in JavaScript

27.11.2023
Reading time: 6 min
Hostman Team
Technical writer

Searching in an array is not a difficult task for a programmer. One immediately thinks of searching through a for loop or binary search in a sorted array with "greater than" and "less than" operations defined for its elements. But like any high-level programming language, JavaScript offers the developer built-in functions to solve various problems. In this article, we'll look at four JavaScript array search methods: find, includes, indexOf, and filter.

indexOf

indexOf is a function to search for an element in an array. This method searches for the object and returns its index or -1 if it does not find a matching one.

Syntax

Array.indexOf (search element, starting index)

Where:

  • Array is our array

  • search element is the element we are searching for;

  • starting index is the index from which we start the search. This argument is optional. By default, the function starts at index 0, i.e., the method checks the whole Array. If the starting index is greater than or equal to Array.length, the method immediately returns -1 and terminates. 

If the starting index is negative, JS treats it as an offset from the end of the array: if the starting index = -1, only the last element will be checked; if -2, then the last two, etc. 

Practice

Let's try the method in practice. Let's run this code and check the results:

let ExampleArray = [1,2,3,1,'5', null, false, NaN,3];

console.log("Position of 1", ExampleArray.indexOf(1) );
console.log("Position of the next 1", ExampleArray.indexOf(1,2) );
console.log("Position of 3", ExampleArray.indexOf(3) );
console.log("Position of 3 if starting index is negative", ExampleArray.indexOf(3,-2) );
console.log("Position of false", ExampleArray.indexOf(false) );
console.log("Position of 5", ExampleArray.indexOf("5") ); 
console.log("Position of NaN", ExampleArray.indexOf(NaN));

As a result of this code's operation, we obtained the following output: 

Position of 1 0
Position of the next 1 3
Position of 3 2
Position of 3 if starting index is negative 8
Position of false 6
Position of 5 -1
Position of NaN -1

indexOf searches for an element in the array from left to right and stops at the first matching element. This is clearly shown in the example with 1. To go from right to left, use the LastIndexOf method with a similar syntax.

Strict comparison (===) is used to compare the object we're searching for and the next object. When using strict comparison for different data types but with the same value, for example 5, '5' and "5" JavaScript gives a negative result, so IndexOf did not find 5

It's also worth remembering that indexOf does not handle NaN correctly. So, you need to use other methods to work with this value.

includes

includes does not exactly search for a given element in the array, but checks if it is there at all. It works in the same way as indexOf. includes returns True if it found the searched item and False if it didn't. Unlike indexOf, includes handles NaN correctly.

Syntax

Array.includes (search element, starting index)

Where: 

  • Array is our array

  • search element is the element we are searching for

  • starting index is the index from which we start searching. It's an optional argument; by default, the function starts at index 0, i.e., the method checks the whole Array. If the starting index is greater than or equal to Array.length, the method immediately returns False and terminates.  

If the starting index is negative, JS treats it as an offset from the end of the array: if the starting index = -1 only the last element will be checked; if -2 , then the last two elements will be checked, etc.

Practice

Let's slightly modify the code from the previous example and run it:

let Example = [1,2,3,1,'5', null, false,NaN, 3];

console.log("Presence of 1", Example.includes(1) );
console.log("Availability of the next 1", Example.includes(1,2) );
console.log("Presence of 3", Example.includes(3) );
console.log("Presence of 3 if starting index is negative", Example.includes(3,-1) );
console.log("Presence of false", Example.includes(false) );
console.log("Presence of 5", Example.includes(5) ); 
console.log("Presence of NaN", Example.includes(NaN) ));

Output:

Presence of 1 true
Presence of the next 1 true
Presence of 3 true
Presence of 3 if the starting index is negative true
Presence of false true
Presence of 5 false
Presence of NaN true

There is no alternative function that searches the JS array from right to left, which is not really necessary.

find

Suppose we need to find an object in an array. But we want to find it not by its value, but by its property. For example, we want to find a number in an array with a value between 15 and 20. As before, we can use a for loop, but it's not very convenient. To search with a specific condition, JavaScript has a find method.

Syntax

Array.find(function(...){
//if the item matches the condition (true), the function returns it and terminates;
//if nothing is found, it returns undefined
})

 Here:

  • Array is our array

  • function(...) is a function that sets the conditions.

Practice

As in the past examples, let's try out the method:

let ExampleArray = ["Hostman", 55555, "Cloud", "server provider", "guide"];
console.log(ExampleArray.find(element => element.length == 5))

Output:

Cloud

In this example, we searched for strings with a length of 5 characters. For numeric data types, the length is undefined, so 55555 is not appropriate. Find finds the first element and returns it, so guide was also not included in the result of our function. To find several elements that match a condition, we need to use the filter method.

Also, we should not forget about the findIndex method. It returns the index of the matching element. Or -1 if there is none. Otherwise, it works the same way as find.

filter

find searches for and returns the first element that matches the search conditions. In order to find all such elements, you need to use the filter method. The result of this function is an array (if nothing is found, it will be empty).

Syntax

Array.find(function(...){
//if the element matches the conditions (true), then add it to the final result and continue the search;
})

 Here:

  • Array is our array

  • function(...) is the function that sets the conditions.

Practice

Let's imagine the following task: we have a list of cuboids (rectangular parallelepipeds) with the lengths of their edges, and we need to output all cuboids with a certain volume. Let's write the code that realizes the solution of this task:

let ExampleArray = [
  [10, 15, 8],
  [11, 12, 6],
  [5, 20, 1],
  [10, 10, 2],
  [16,2, 4]
  ];

console.log(ExampleArray.filter(element=> element[0]*element[1]*element[2]>300)))

Output:

[ [ 10, 15, 8 ],
[ 11, 12, 6 ] ]

In this example, we found rectangular parallelepipeds with a volume greater than 300. In general, the filter method in JS allows you to implement all kinds of search conditions. 

Conclusion

In this article, we have learned about search methods in JavaScript and how to use them. All the above methods are universal tools for developers. But, like any universal tools, they are not always the most productive. For example, binary search will be much more efficient than find and filter.