Add and search
- TypeScript course
- Beginner
- Lesson 82/89
- 5 min
Write book add and search functions.
The addBook function
The addBook function adds a new Book object to the library. You append it to the end of the array with push.
function addBook(lib: Library, book: Book): void {
lib.books.push(book);
}The searchByTitle function
searchByTitle finds books whose title contains a specific term. You use filter and check each book's title with includes.
function searchByTitle(lib: Library, title: string): Book[] {
return lib.books.filter(b => b.title.includes(title));
}Practice Write add and search
Define Book, Member, Library interfaces. Write a function addBook(lib: Library, book: Book): void. Write a function searchByTitle(lib: Library, title: string): Book[]: search titles with filter and includes. Add two books ("TypeScript", "JavaScript") and search for "Script", print the number of matches.
Starter code
// Book, Member, Library arayüzlerini tanımla
// addBook(lib: Library, book: Book): void yaz
// searchByTitle(lib: Library, title: string): Book[] yaz
// iki kitap ekle, bir başlıkla ara ve eşleşen sayısını yazdırSample solution
interface Book { id: string; title: string; author: string; available: boolean; }
interface Member { id: string; name: string; }
interface Library { books: Book[]; }
function addBook(lib: Library, book: Book): void {
lib.books.push(book);
}
function searchByTitle(lib: Library, title: string): Book[] {
return lib.books.filter(b => b.title.includes(title));
}
const lib: Library = { books: [] };
addBook(lib, { id: "b1", title: "TypeScript", author: "Ada", available: true });
addBook(lib, { id: "b2", title: "JavaScript", author: "Bob", available: true });
const results = searchByTitle(lib, "Script");
console.log(results.length);Expected output
2
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does the searchByTitle function return?
- void
- A single Book
- number
- Book[] (matching books) Correct answer
Explanation: searchByTitle returns all books whose title contains the search term as a new array. filter always returns a new array.
2 Complete the includes call
return lib.books.filter(b => b.title.____(title));
return lib.books.filter(b => b.title.includes(title));
Explanation: The string includes method checks whether a substring is present. find is an array method; has and contains do not exist on strings.
3 Add and search parts
| Term | Meaning |
|---|---|
addBook |
Add a book to the library |
searchByTitle |
Search by title |
lib.books.push(book) |
Push a book to the list |
b.title.includes(title) |
Title check |