DEV Community

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

Posted on

2

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.

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs