Build a Book Organizer - Build a Book Organizer

Tell us what’s happening:

Why does my code as written work, but if I chain the sort function like this it doesn’t?:

let filteredBooks = books
.filter((book) => book.releaseYear < 2023)
.sort(sortByYear);

Your code so far

let books = [
  {
    title: "Book1",
    authorName: "Author1",
    releaseYear: 2021,
  },
  {
    title: "Book2",
    authorName: "Author2",
    releaseYear: 2022,
  },
  {
    title: "Book3",
    authorName: "Author3",
    releaseYear: 2023,
  }
];
function sortByYear(book1, book2) {
  if (book1.releaseYear < book2.releaseYear) {
    return -1;
  }
  if (book1.releaseYear > book2.releaseYear) {
    return 1;
  }
  return 0;
}

let filteredBooks = books
  .filter((book) => book.releaseYear < 2023);

console.log(filteredBooks);
filteredBooks.sort(sortByYear);

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.1 Safari/605.1.15 Ddg/26.1

Challenge Information:

Build a Book Organizer - Build a Book Organizer

What do you mean “work” or “doesn’t work” ? Is there an error?

What would be the first step in investigating this?

When trying the chained method, I got an error message saying I needed to call sort and pass the sortByYear function and the test fails that step. I tested by checking to ensure that the filtered array was created correctly, which it was. I thought I understood that when chaining functions, the result of the first is passed to the second, so I’m confused about why it’s not working.

const filteredBooks = books.filter(book => book.releaseYear < 2023).sort(sortByYear);
console.log(filteredBooks);

Your code with this change works as expected in VS Code. Apparently, the tests don’t expect chaining for this challenge.

1 Like

OK, thanks for letting me know. I’m trying to get all the details straight :grinning_face:

I almost think the tests should accept your answer here as well. It looks like they are too specific here.

However, if you are implementing the User Stories one at a time, it’s 2 steps:

  1. You should filter out books written after a certain year such as 1950 from the books array and save the filtered array in a new array named filteredBooks.
  1. You should sort the books in the filteredBooks array according to their releaseYear in ascending order. You learned in a prior lesson that the sort() method will sort the array in place. This means the filteredBooks array will be mutated.

If you chain this, then you aren’t really completing User Story 7.

The end result is the same, but the User Stories aren’t really implemented exactly as they are written.

I can see how the way the 2 user stories are written imply not chaining. The fact that it worked in VSCode is really the relevant point — the chaining logic works, it just doesn’t meet the test requirements. Thanks again :grinning_face:

1 Like

Thanks! I ran into this same issue.