LastIndexOf() Function

In Google Apps Script, the lastIndexOf() 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 end and returns the index of the last occurrence of the specified element.

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

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

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

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

In this example, we call the lastIndexOf() method on the countries array to search for the element "Brazil". The method returns the index of the last occurrence of "Brazil" in the array, which is 5. 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 lastIndexOf() 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 },
  { name: "Jane", age: 35 }
];

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

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

In this example, we call the map() method on the persons array to create a new array containing only the name property of each object. Then, we call the lastIndexOf() method on the new array to search for the value "Jane". The method returns the index of the last occurrence of "Jane" in the new array, which is 3. The index is assigned to a variable called index, which is outputted to the log using the Logger.log() method.