To find index of an element in an array javascript; In this tutorial, you will learn how to find the position or index of an element in an array using JavaScript array indexOf()
and lastIndexOf()
methods.
How to find index of an element in an array javascript
- JavaScript Array
indexOf()
- JavaScript Array
lastIndexOf()
JavaScript array indexOf()
The indexOf()
method is used to find the first occurrence position of an array And returns the index of the first occurrence of the element. If the element is not found, -1 return.
Syntax of the indexOf()
:
Array.indexOf(search, startIndex)
Here, the indexOf()
method accepts two parameters.
- The
search
argument is the element that you want to find in the array. - The
startIndex
is an array index at which the function starts the search.
Note:- The startIndex
parameter value can be a positive or negative integer.
Example JavaScript array indexOf()
Take look examples of indexOf() method:
Suppose, you have a numeric array named arr
. See the following:
var arr = [10, 20, 30, 40, 50, 70, 10];
The following example uses the indexOf()
method to find the elements in the arr
array:
var arr = [10, 20, 30, 40, 50, 70, 10, 50];
console.log(arr.indexOf(10)); // 0
console.log(arr.indexOf(50)); // 4
console.log(arr.indexOf(70)); // 5
console.log(arr.indexOf(30)); // 2
If you have the following array of objects, where each object has different properties. See the following:
var obj = [
{name: 'John Doe', age: 30},
{name: 'Tom Bush', age: 20},
{name: 'Bill Gate', age: 25}
];
The following statement returns -1
even though the first element of the obj
array and the searchElement
have the same values in the name
and ages
properties. This is because they are two different objects.
console.log(obj.indexOf({
name: 'John Doe',
age: 30
})); // -1
JavaScript array lastIndexOf()
This is similar to the indexOf() method, but one difference in these. The Javascript lastIndexOf() method is used to find the last occurrence position of an array. It returns -1 if it cannot find the element.
Syntax of the lastIndexOf()
method:
Array.lastIndexOf(searchElement[, fromIndex = Array.length - 1])
Note:- The basic different from the indexOf()
method and the lastIndexOf()
method. One is backword search method and another is forward search method.
See the following example:
var arr = [10, 20, 30, 40, 50, 70, 10, 40];
console.log(arr.lastIndexOf(10));// 6
console.log(arr.lastIndexOf(40));// 7
If finding elements in the array, and it is not available in it, returns -1. See the following:
var arr = [10, 20, 30, 40, 50, 70, 10, 40];
console.log(arr.lastIndexOf(100));// -1
Conclusion
In this tutorial, you have learned how to use the JavaScript array indexOf()
and lastIndexOf()
methods to find the elements in an array.