Searching in an Array in JavaScript


This content was proof-read by Grammarly. You can Try Grammary for FREE

If you want to search an array for a value in JavaScript and retrieve the index of the found array element , you can use the Array’s indexOf method.

How to search for an element in an array in JavaScript ?

When using the indexOf method , if the value is found, it returns the index representing the array element. If the value is not found, then the value –1 is returned.

Below is a sample code snippet demonstrating the search of an element in a array using indexOf method.

<script type="text/javascript">
    var players = new Array('Sachin Tendulkar', 'Virat Kohli', 'Dhoni');
    console.log(players.indexOf('Dhoni'));
</script>
How to search for an element in an array in JavaScript ?
Newsletter Signup

Subscribe to our weekly newsletter below and never miss the latest product or an exclusive offer.

Newsletter Signup

Subscribe to our weekly newsletter below and never miss the latest product or an exclusive offer.

%d bloggers like this: