Array Methods

Methods for Searching

🙋 Need help? Ask an expert now!

There are many methods that can help you find specific elements in an array. The indexOf(), lastIndexOf, find(), and findIndex() method all help you find elements of an array. The syntax and the function of each method is show below.

arrayname.indexOf(element, [rightOf])

  • returns the index of the first match in the array
  • returns -1 is the element is not found

arrayname.lastIndexOf(element, [leftOf])

  • returns the index of the first match in the array
  • returns -1 is the element is not found

arrayname.find(function)

  • returns the leftmost element in the array, that meets the criteria in the function
  • if no such element is found, returns undefined

arrayname.findIndex(function)

  • returns the index of the leftmost element in the array, that meets the criteria in the function
  • if no such element is found, returns -1

Let's take a look at the methods one at a time. The indexOf() method prints the first index of the digit 2 after index 0. This is why 1 is printed to the console. The lastIndexOf() method prints the last available index of the digit 2, which is 9, the last index of arr 1. The find() method finds the first even number in the array and prints the element to the console. The findIndex() methods finds the first even number in the array and prints the index of that element. This is why the index 1 is printed on the console. Take some time to digest these methods and understand how they work.

Edit Me on GitHub!

Application Question

Consider the following code segment:

var arr = [1, 3, 3, 4, 3, 3, 33, 5, 3, 2];
            console.log(arr.lastIndexOf(3, 7));
            

What will the following code segment print to the console?