4.6 Finding an Element in an Array
You will often need to search through the contents of arrays to find where specific elements occur. Take this grocery list as an example:
Suppose you want to find the location of where “bread” occurs in this array. Or suppose you want to find the position of where “paper towels” occurs in the array. How can you do this without having to manually count through each position of the array yourself?
You will recall that each individual location or position in an array is called an index. The starting index in an array is always 0. Thus, “bread” occurs in this array at index 0. The remaining indices are numbered consecutively up until the last element in the array. For example, “lettuce” occurs at index 6.
You can find the index of any element in an array with two techniques: 1) by writing your own indexOf()
function, 2) by using JavaScripts built in indexOf()
method. Let’s look at both options!
Let’s say you are given this as a start()
function to work with:
This code will not run because you first need to define your own indexOf()
function:
The indexOf()
function takes in an array, arr
, and a string to search for within the array, str
. You begin by looping through the contents of the array using for
loop iteration. On each iteration, you get the current element using arr[i]
and store it into a variable called cur
. You then check to see if the current element, cur
, is equal to the string you are searching for, str
. If it is, you return the index as kept track by your for loop variable, i
.
However, if the element is not found after searching through the entire array, you return -1
. Why -1? Because an array’s index can’t be negative! This tells you that the element is not in the array at all.
Now let’s add your function to the original program and find the location of a few items:
What will get printed to the screen? What index values will be returned for each of these items?
Answer:
Since apple juice is not in the list at all, it returns -1.
Javascript actually has an indexOf()
method of its own that you can use: arrayName.indexOf(str);
You can use this example to check if the results match the indexOf()
function that you built yourself.
When you run this program, you will see that the results are indeed identical! While it’s important to know how to write your own function to search an array, using JavaScript’s built-in method makes it easy!
-
Incorrect
Correct
No Answer was selected
Invalid Answer
What will be the result of
pets.indexOf("hamster");
when applied to the array below?“`javascript
var pets = [“hamster”, “dog”, “cat”, “mouse”, “parrot”, “turtle”];
“
You are given an array of names of people who are in line. Try using if statements and the indexOf
method of arrays to see if Tony is in line.
You should print whether Tony is in each line. Your console should print something like this: