Filter By Genre
Part of the Logic & Flow section of Coddy's JavaScript journey — lesson 45 of 65.
Challenge
EasyAdd a new case filterByGenre to your switch statement. This action should filter books by their genre.
For the filterByGenre case:
- The
currentDataparameter is a string representing the genre to filter by - Create an empty array
filteredResultsto store the filtered results - Loop through all books in the library
- For each book, check if its genre exactly matches the requested genre
- If there's a match, add the book to the
filteredResultsarray - Add the
filteredResultsto the mainresultsarray
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
1Strings In Depth
String FundamentalsIterate Over StringsTemplate LiteralsString MethodsRecap - String Weaver4JSON Part 2
Iterate Over JSONNested JSONJSON Optional ChainingShallow And Deep CopyRecap - Bicycle ShopRecap - Solar System10Manage Festival System
Project OverviewAdd Movies & Venues2Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysMatrix Addition & SubstractionJagged Arrays3D Arrays And BeyondCommon 2D Array PatternsRecap - All About Arrays5Sets Part 1
What Is A Set?Iterating Over SetsAdding An ElementRemoving An ElementChecking If An Element ExistsSize And Is EmptyCopy And ClearRecap - Basic Of Sets8Arrays Interesting Topics
Array DestructuringSpread Syntax in ArraysSparse ArraysRecap - Arrays Workshop3JSON Part 1
What is a JSON?Check If Key ExistsObject MethodsThe Spread Operator Part 1The Spread Operator Part 2Remove KeysRecap - JSON Manipulate Keys