JavaScript array indexOf() Method returns the first index at which the given element can be found in an array or -1 if the item is not found.
Syntax
array.indexOf(element, start)
Parameters
- element(required): It is the element to search for in the array.
- start(optional): It is the position where to start the search. The default value is 0.
Return Value
It returns the integer, the index of an element in the Array. -1 if the element is not present.
Visual Representation
Example 1: How to Use Array indexOf() method
let letters = ['A', 'B', 'C', 'D', 'E', 'F'];
console.log(letters.indexOf('D'));
console.log(letters.indexOf('F'));
console.log(letters.indexOf('Z'));
Output
3
5
-1
Example 2: Using the start parameter
let letters = ['A', 'B', 'C', 'D', 'A', 'B'];
console.log(letters.indexOf('A',2));
console.log(letters.indexOf('B',0));
Output
4
1
Example 3: How to get an indexof objects in an array
To get an index of an array that contains objects, you can use the “map()” method. See the following code example in which we will find the index of a mike, which is 0 basically because when we add the two objects in the Array, st is the first object, meaning its index is 0.
let st = {
mike: 'Finn',
el: 'Millie'
};
let got = {
jon: 'Kit',
khaleesi: 'Emilia'
}
let arr = [];
arr.push(st, got);
pos = arr.map(function(e) { return e.mike; }).indexOf('Finn');
console.log(pos);
Output
0
Example 4: Case sensitive
To search an element in the array regardless of its case sensitivity, use the “array findIndex()” and “toLowerCase()” methods.
let arr = ['miLLie', 'fiNN', 'saDiE', 'caLEB', 'gaTEn'];
query = 'caleb',
pos = arr.findIndex(item => query.toLowerCase() === item.toLowerCase());
console.log(result);
Output
3
Browser Compatibility
- Google Chrome 1 and above
- Edge 12 and above
- Firefox 1.5 and above
- Opera 9.5 and above
- Safari 3 and above
Recommended Posts
JavaScript array lastIndexOf()
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.