indexOf JavaScript

The JavaScript array indexOf method, returns the starting position of an element within an array or string.

The syntax of this method is as follows: array.indexOf(element)

Where element is therefore the element whose position you want to know.

As with the includes method, also in this case, you can optionally specify the position from which to start, adding a second parameter as an argument of indexOf.

array.indexOf(element, start).

The method returns a numeric value that corresponds to the position of the element in the array or string.

JavaScript array indexOf – example 1

We know the position of an element in an array using the indexOf () method.

So let’s suppose we have the following array:



var objectsSchools = ['eraser', 'notebook', 'pencil'];

We then apply the indexOf method to know, for example, the position of the notebook element.



var result = objectsSchools.indexOf('notebook');
console.log(result);

In the browser console I will display the value 1 which corresponds to the position of the element.

JavaScript array indexOf – example 2

Display all even-numbered elements of an array using the indexOf method.

This algorithm can also be solved in other ways. Here we will use the indexOf method to analyze another scope of the following method.

Let’s create an array of integers. Then, with a for loop, we analyze the position of each element, checking if it is an even number. To do this, we use, as seen in previous years, the modulo (%) operator and calculate the remainder of the division of the number divided by 2.

So only if it is even we display the number, for simplicity, in the browser console.

So here is the example code of the JavaScript indexOf method:


var arrayNumbers = [6,12,34,67,89,98,5,2,7,13];
console.log (arrayNumbers);
for (var i = 0; i < arrayNumbers.length; i ++) {
  if (arrayNumbers.indexOf(arrayNumbers[i]) % 2 == 0) {
    console.log(arrayNumbers[i]);
  }
}

We also recall that the same algorithm could be solved simply in this way:


for (var i = 0; i < arrayNumbers.length; i ++) {
  if (arrayNumbers[i] % 2 == 0) {
    console.log(arrayNumbers[i]);
  }
}

Conclusion

In this lesson we have dealt with two simple examples of using the JavaScript array indexOf method, in the next lessons I will propose other examples.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

Lascia un commento

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *