jQuery inArray() method
This inArray() Method in jQuery is used to search for a specific value in an array and return its index (or -1 if not found).
Syntax
jQuery.inArray(val, arr [, Index])
Parameters
The inArray() method accepts three parameters that are described below:
- val: The value to search in an array.
- arr: Any array like object.
- Index: Index of the array from which to begin search.
Return Value
It returns the index of element in an array, or -1 if element not found.
Example 1: In this example, the inArray() method searches an element 30 in the array.
<!DOCTYPE HTML>
<html>
<head>
<title>
jQuery inArray() Method
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js">
</script>
</head>
<body>
<script>
let arr = [10, 20, 30, 40, 50, 60];
let val = 30;
let index = $.inArray(val, arr);
console.log(index);
</script>
</body>
</html>
Console Output:
2
Example 2: In this example, the inArray() method searches an element 30 in the array. The index attribute is also passed to search the element from index 3 and return -1.
<!DOCTYPE HTML>
<html>
<head>
<title>
jQuery inArray() Method
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js">
</script>
</head>
<body>
<script>
let arr = [10, 20, 30, 40, 50, 60];
let val = 30;
let index = $.inArray(val, arr, 3);
console.log(index);
</script>
</body>
</html>
Console Output:
-1
Contact Us