Console
Coding Workspace
interface Book {
  title: string;
  author: string;
}

export const sortBooksByTitle = (books: Book[]) => {
  // Create a shallow copy of the array to avoid modifying the original array
  return books.slice().sort((a, b) => {
    // Secondary comparison on authors if titles are the same
    const authorA = a.author.toLowerCase();
    const authorB = b.author.toLowerCase();
    if (authorA < authorB) return -1;
    if (authorA > authorB) return 1;

    // Convert titles to lowercase to achieve case-insensitive comparison
    const titleA = a.title.toLowerCase();
    const titleB = b.title.toLowerCase();

    // Primary comparison on titles
    if (titleA < titleB) return -1;
    if (titleA > titleB) return 1;

    return 0; // If authors are also the same, keep original order
  });
};

// Example usage with books array
const books: Book[] = [
  { title: "The Great Gatsby", author: "F. Scott Fitzgerald" },
  { title: "Moby Dick", author: "Herman Melville" },
  { title: "1984", author: "George Orwell" },
  { title: "a Farewell to Arms", author: "Ernest Hemingway" },
];

const sortedBooks = sortBooksByTitle(books);
console.log(sortedBooks);
Level:
beginner

Books Sorted by Author Instead of Title

When using the sortBooksByTitle function, users may notice that books are sorted by the author's name rather than by the title. This sorting behavior is contrary to typical expectations where the primary sorting criterion for books should be the title, followed by the author only if titles are identical.

Steps to Reproduce

  1. Define an array of books with distinct titles and authors.
  2. Invoke the sortBooksByTitle function with the defined books array.
  3. Examine the output to determine the primary sorting criterion based on the order of the books.

Expected Behavior

Users expect the function to sort books primarily by their titles, making it easy to find books alphabetically by title. The function should only consider the author's name when the titles are the same, ensuring that titles are the foremost sorting criterion.

Need help?

Open browser consoleTests