Searching an array
The JavaScript API provides a few different methods we can use to search or find elements in an array. Although we will learn how to re-create classic algorithms to search elements in Chapter 15, Searching and Shuffling Algorithms, it is always good to know we can use existing APIs without having to write the code ourselves.
Let's take a look at the existing JavaScript methods that allows us to search elements in an array.
Searching with indexOf, lastIndexOf and includes methods
The methods indexOf
, lastIndexOf
and includes
have a very similar sintax as follows:
indexOf(element, fromIndex)
: searches for theelement
starting from the indexfromIndex
, and in case the element exists, returns its index, otherwise returns the value-1
.includes(element, fromIndex)
: searches for theelement
starting from the indexfromIndex
, and in case the element exists, returnstrue
, otherwise returnsfalse
.
If we try to search for a number in our numbers
array, let's check...