Menu
Coddy logo textTech

Filter By Genre

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

challenge icon

Challenge

Easy

Add a new case filterByGenre to your switch statement. This action should filter books by their genre.

For the filterByGenre case:

  1. The currentData parameter is a string representing the genre to filter by
  2. Create an empty array filteredResults to store the filtered results
  3. Loop through all books in the library
  4. For each book, check if its genre exactly matches the requested genre
  5. If there's a match, add the book to the filteredResults array
  6. Add the filteredResults 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;
            case "searchByTitle":
                // Search for books by title
                let searchResults = [];
                for(let i = 0; i < libraryData.books.length; i++) {
                    if(libraryData.books[i].title.toLowerCase().includes(currentData.toLowerCase())) {
                        searchResults.push(libraryData.books[i]);
                    }
                }
                results.push(searchResults);
                break;
            default:
                results.push("Invalid action!");
        }
    }

    return results;
}

All lessons in Logic & Flow