This is the prompt:
“The getBooksBorrowedCount()
function in public/src/home.js
has a single parameter:
- An array of books.
It returns a number that represents the number of books that are currently checked out of the library. This number can be found by looking at the first transaction in the borrows
key of each book. If the transaction says the book has not been returned (i.e. returned: false
), the book has been borrowed.”
What I have tried:
function getBooksBorrowedCount(books){ for (let i = 0; i < books.length; i++) { if (books[i].returned === true) { return books[i]; } } return null; }
Every time I run this code I receive an error stating that “expected null to equal 6” for the life of me i cannot figure this out, I need some help.
Example Data is listed here:
const books = [{id: "5f447132d487bd81da01e25e", title: "sit eiusmod occaecat eu magna", genre: "Science", authorId: 8, borrows: [ { id: "5f446f2e2cfa3e1d234679b9", returned: false, }, { id: "5f446f2ed3609b719568a415", returned: true, }, { id: "5f446f2e1c71888e2233621e", returned: true, }, { id: "5f446f2e6059326d9feb9a68", returned: true, }, { id: "5f446f2ede05a0b1e3394d8b", returned: true, }, { id: "5f446f2e4081699cdc6a2735", returned: true, }, { id: "5f446f2e3900dfec59489477", returned: true, }, { id: "5f446f2e6059326d9feb9a68", returned: true, }, { id: "5f446f2e409f8883af2955dd", returned: true, }, { id: "5f446f2e3900dfec59489477", returned: true, }, { id: "5f446f2eae901a82e0259947", returned: true, }, { id: "5f446f2ef2ab5f5a9f60c4f2", returned: true, }, { id: "5f446f2ea6b68cf6f85f6e28", returned: true, },
Advertisement
Answer
You have to access the first borrows
array item to get your data
const books = [{ id: "5f447132d487bd81da01e25e", title: "sit eiusmod occaecat eu magna", genre: "Science", authorId: 8, borrows: [{ id: "5f446f2e2cfa3e1d234679b9", returned: false, }, { id: "5f446f2ed3609b719568a415", returned: true, }, { id: "5f446f2e1c71888e2233621e", returned: true, }, { id: "5f446f2e6059326d9feb9a68", returned: true, }, { id: "5f446f2ede05a0b1e3394d8b", returned: true, }, { id: "5f446f2e4081699cdc6a2735", returned: true, }, { id: "5f446f2e3900dfec59489477", returned: true, }, { id: "5f446f2e6059326d9feb9a68", returned: true, }, { id: "5f446f2e409f8883af2955dd", returned: true, }, { id: "5f446f2e3900dfec59489477", returned: true, }, { id: "5f446f2eae901a82e0259947", returned: true, }, { id: "5f446f2ef2ab5f5a9f60c4f2", returned: true, }, { id: "5f446f2ea6b68cf6f85f6e28", returned: true, } ] }] function getBooksBorrowedCount(books) { let count = 0 for (let i = 0; i < books.length; i++) { if (books[i].borrows[0].returned !== true) count++ } return count; } console.log(getBooksBorrowedCount(books)) //Another way of doing this with less code: let numBooksBorrowed = 0; books.forEach(book => { if (!book.borrows[0].returned) numBooksBorrowed++; }); console.log(numBooksBorrowed)