Please enable JavaScript to use CodeHS

Chapter 4

Basic Data Structures

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:

var list = ["bread", "eggs", "milk", "cookies", "bananas",  "tuna", "lettuce", "yogurt", "cheese", "chicken", "cucumbers",  "orange juice", "salt", "Doritos", "lemonade", "apples", "paper towels", "red onion", "minced garlic", "turmeric",  "donuts", "bagels", "crackers", "red pepper", "green pepper",  "spinach", "canola oil", "vanilla", "flour", "brown sugar", "powdered sugar", "lime"];
JavaScript

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!

Writing an Array indexOf Function

Let’s say you are given this as a start() function to work with:

function start(){
    var list = ["bread", "eggs", "milk", "cookies", "bananas",  "tuna", "lettuce", "yogurt", "cheese", "chicken", "cucumbers",  "orange juice", "salt", "Doritos", "lemonade", "apples", "paper towels", "red onion", "minced garlic", "turmeric",  "donuts", "bagels", "crackers", "red pepper", "green pepper",  "spinach", "canola oil", "vanilla", "flour", "brown sugar", "powdered sugar", "lime"];

    var idx = indexOf(list, "bread");
    println("The index of bread is: " + idx);
}
JavaScript

This code will not run because you first need to define your own indexOf() function:

function indexOf(arr, str){
    for(var i = 0; i < arr.length; i++){
        var cur = arr[i];
        if(cur == str){
            return i;
        }
    }
 return -1;
}
JavaScript

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:

function start(){
    var list = ["bread", "eggs", "milk", "cookies", "bananas",  "tuna", "lettuce", "yogurt", "cheese", "chicken", "cucumbers",  "orange juice", "salt", "Doritos", "lemonade", "apples", "paper towels", "red onion", "minced garlic", "turmeric",  "donuts", "bagels", "crackers", "red pepper", "green pepper",  "spinach", "canola oil", "vanilla", "flour", "brown sugar", "powdered sugar", "lime"];

    var idx = indexOf(list, "bread");
    println("The index of bread is: " + idx);

    println("The index of lettuce is: " + indexOf(list, "lettuce"));
    println("The index of paper towels is: " + indexOf(list, "paper towels"));
    println("The index of apple juice is: " + indexOf(list, "apple juice"));
}

function indexOf(arr, str){
    for(var i = 0; i < arr.length; i++){
        var cur = arr[i];
        if(cur == str){
            return i;
        }
    }
 return -1;
}
JavaScript

What will get printed to the screen? What index values will be returned for each of these items?

Answer:

The index of bread is: 0
The index of lettuce is: 6
The index of paper towels is: 16
The index of apple juice is: -1
Plain text

Since apple juice is not in the list at all, it returns -1.

Array indexOf

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!

Check Your Understanding

  1. 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”];

Exercise: Who is in Line?

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.

var line = ["Sam", "Lisa", "Laurie", "Bob", "Ryan"];

var line2 = ["Tony", "Lisa", "Laurie", "Karen"];
JavaScript

You should print whether Tony is in each line. Your console should print something like this:

Tony is not in the first line.
Tony is in the second line.
Plain text