JavaScript Array indexOf() Method

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

  1. element(required): It is the element to search for in the array.
  2. 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 RepresentationVisual Representation of JavaScript Array indexOf() Method

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 parameterVisual Representation of 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

  1. Google Chrome 1 and above
  2. Edge 12 and above
  3. Firefox 1.5 and above
  4. Opera 9.5 and above
  5. Safari 3 and above

Recommended Posts

JavaScript array find()

JavaScript array lastIndexOf()

JavaScript array filter()

JavaScript array forEach()

JavaScript array toString()

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.