Finding in a List: indexOf
Part of the Logic & Flow section of Coddy's Dart journey — lesson 6 of 65.
When you need to find where a specific element is located in a list, Dart provides the indexOf() method. This method searches through the list and returns the index position of the first occurrence of the element you're looking for.
The indexOf() method takes the element you want to find as its parameter and returns an integer. If the element exists in the list, it returns the index position (starting from 0). If the element is not found, it returns -1.
List<String> fruits = ['apple', 'banana', 'orange', 'banana'];
int appleIndex = fruits.indexOf('apple'); // 0
int bananaIndex = fruits.indexOf('banana'); // 1 (first occurrence)
int grapeIndex = fruits.indexOf('grape'); // -1 (not found)This method is particularly useful when you need to know the position of an item before performing operations like insertion or removal at specific locations. Remember that indexOf() only finds the first match, so if an element appears multiple times, you'll get the index of its first occurrence.
Challenge
EasyCreate a program that manages a library book search system by finding the location of specific books on the shelves. Your program should:
- Read a string input representing the library section name
- Read multiple string inputs representing book titles on the shelf (the input will end when you receive an empty string)
- Read a string input representing the book title to search for
- Use the
indexOf()method to find the position of the requested book - Print the search results in the exact format shown below
For example, if the library section is "Science Fiction", the books are "Dune", "Foundation", "Neuromancer", "Foundation", "Ender's Game", and the search book is "Foundation", your program should output:
Library Section: Science Fiction
Books on shelf: [Dune, Foundation, Neuromancer, Foundation, Ender's Game]
Searching for: Foundation
Book found at position: 1
Status: Book located successfullyIf the library section is "Mystery", the books are "Sherlock Holmes", "Agatha Christie", "The Maltese Falcon", and the search book is "Gone Girl", your program should output:
Library Section: Mystery
Books on shelf: [Sherlock Holmes, Agatha Christie, The Maltese Falcon]
Searching for: Gone Girl
Book found at position: -1
Status: Book not availableYour program must use the indexOf() method to search for the book. When the book is found (position >= 0), display "Book located successfully". When the book is not found (position = -1), display "Book not available". Remember that indexOf() returns the position of the first occurrence if the book appears multiple times.
Cheat sheet
Use indexOf() to find the position of an element in a list:
List<String> fruits = ['apple', 'banana', 'orange', 'banana'];
int appleIndex = fruits.indexOf('apple'); // 0
int bananaIndex = fruits.indexOf('banana'); // 1 (first occurrence)
int grapeIndex = fruits.indexOf('grape'); // -1 (not found)The method returns the index position (starting from 0) if found, or -1 if the element doesn't exist. It only finds the first occurrence of duplicate elements.
Try it yourself
import 'dart:io';
void main() {
// Read library section name
String? section = stdin.readLineSync();
// Read book titles until empty string
List<String> books = [];
String? book;
while ((book = stdin.readLineSync()) != null && book!.isNotEmpty) {
books.add(book);
}
// Read the book to search for
String? searchBook = stdin.readLineSync();
// TODO: Write your code below
// Use indexOf() method to find the position of the book
// Print the results in the required format
print('Library Section: $section');
print('Books on shelf: $books');
print('Searching for: $searchBook');
// Print position and status based on your search results
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Advanced List Manipulation
List Properties: first & lastList State: isEmpty & isNotEmpReversing a ListAdding to a List: insertList Removal: removeWhereFinding in a List: indexOfSorting a ListShuffling a ListRecap - List Organizer4Advanced Map Manipulation
Iterating Over a MapChecking for Keys and ValuesMap Properties: keys & valuesConditional Add: putIfAbsentRemoving Entries from a MapNested MapsRecap - Inventory Update2Functional List Operations
Transforming with 'map'Filtering with 'where'Using '.toList()'Checking Conditions with 'any'Conditions with 'every'Finding with 'firstWhere'Recap - Data Filtering5Project: Shopping Cart Calc
Project SetupAdding Items to the Cart3Sets
What is a Set?Creating a SetAdding and Removing from SetsChecking for Elements in a SetConverting a List to a SetSet UnionSet IntersectionSet DifferenceRecap - Unique Guest List