DEV Community

Cover image for A Beginner's Guide to Searching for Elements in Arrays with JavaScript
Nishant Patil
Nishant Patil

Posted on

A Beginner's Guide to Searching for Elements in Arrays with JavaScript

Lets talk about searching an element in an array. There are various algorithm used for this purpose, but the one which I am going to discuss is Linear Search. Linear Search is simple and easy to understand. There is also a default javascript method for for linear search, will will talk about it later.

Linear Search is simple it uses a for loop, which loops through the given array and returns its index. If the index is a value then we know that the value exist , if its undefined then the value is absent.

  let data =[20,40,60,5,10,70,80,99];
        let item=70;
        let index=undefined;

        for(i=0;i<=data.length-1;i++){
             if(data[i]===item)
             {
                index=i;
                 break;
             }
         }
         console.log(index);

         // default method to search an element in array
         console.warn(data.indexOf(item))
Enter fullscreen mode Exit fullscreen mode

You can copy paste the above code and test it.
The defualt funciton used of searching an element in array is indexOf() method. By passing the element that you have in array inside indexOf() method it will return its index.

Top comments (0)