IndexOf() Function

In Google Apps Script, the indexOf() method is an array method that allows you to search for a specified element in an array and returns its index position. The method searches the array from the beginning and returns the index of the first occurrence of the specified element.

Here is an example of using the indexOf() method to search for a country name in an array:

var countries = ["USA", "Canada", "Mexico", "Brazil", "Argentina"];

// Find the index of "Brazil" in the countries array
var index = countries.indexOf("Brazil");

// Output the index
Logger.log(index); // Outputs: 3

In this example, we call the indexOf() method on the countries array to search for the element "Brazil". The method returns the index of the first occurrence of "Brazil" in the array, which is 3. The index is assigned to a variable called index, which is outputted to the log using the Logger.log() method.

You can also use the indexOf() method to search for an object in an array of objects:

var persons = [
  { name: "John", age: 30 },
  { name: "Jane", age: 25 },
  { name: "Bob", age: 40 }
];

// Find the index of the object with name "Jane" in the persons array
var index = persons.findIndex(person => person.name === "Jane");

// Output the index
Logger.log(index); // Outputs: 1

In this example, we call the findIndex() method on the persons array, passing a callback function that returns true when the name property of an object is equal to "Jane". The method returns the index of the first object for which the callback function returns true, which is 1. The index is assigned to a variable called index, which is outputted to the log using the Logger.log() method.