Menu
Coddy logo textTech

Search By Title

Part of the Logic & Flow section of Coddy's JavaScript journey — lesson 44 of 65.

challenge icon

Challenge

Easy

Create a new case searchByTitle in your switch statement. This action should search for books by their title.

For the searchByTitle case:

  1. The currentData parameter is a string to search for
  2. Create an empty array searchResults to store the search results
  3. Loop through all books in the library
  4. For each book, check if its title includes the search string
  5. The search should be case-insensitive (convert both strings to lowercase before comparing)
  6. If a match is found, add the book to the searchResults array
  7. Add the searchResults array to the main results array

Try it yourself

// Initialize library data
const libraryData = {
    books: [
        {
            id: 1,
            title: "The Great Gatsby",
            author: "F. Scott Fitzgerald",
            year: 1925,
            genre: "Fiction",
            isRead: false,
            rating: 0,
            borrowed: false,
            borrowedBy: "",
            borrowDate: ""
        }
    ],
    readers: [
        {
            name: "John Smith",
            favoriteGenre: "Fiction",
        }
    ]
};

function manageLibrary(actions, data) {
    let results = [];
    
    for (let i = 0; i < actions.length; i++) {
        const currentAction = actions[i];
        const currentData = data[i];
        
        switch (currentAction) {
            case 'printBooks':
                results.push(libraryData.books);
                break;
            case 'printReaders':
                results.push(libraryData.readers);
                break;
            case "addBook":
                // Add a new book to the library
                let newBook = {
                    id: libraryData.books.length + 1,
                    title: currentData.title,
                    author: currentData.author,
                    year: currentData.year,
                    genre: currentData.genre,
                    isRead: false,
                    rating: 0,
                    borrowed: false,
                    borrowedBy: "",
                    borrowDate: ""
                };
                libraryData.books.push(newBook);
                results.push("Book added successfully!");
                break;
            default:
                results.push("Invalid action!");
        }
    }
    
    return results;
}

All lessons in Logic & Flow