-1

I have an array of objects in JavaScript, and I want to sort them based on a specific property of the objects. For example, I have an array of books, and each book object has properties like 'title', 'author', and 'publicationYear'. How can I sort this array of book objects alphabetically by the 'title' property?

Here's a simplified version of the array:

    const books = [
    { title: 'The Great Gatsby', author: 'F. Scott Fitzgerald', publicationYear: 1925 },
    { title: 'To Kill a Mockingbird', author: 'Harper Lee', publicationYear: 1960 },
    { title: '1984', author: 'George Orwell', publicationYear: 1949 }
];

This array should be sorted ascendingly using the 'title' parameter. I attempted to discover the answer by going to several sites like scaler, but I was unable to locate the solution. Could you supply a JavaScript code sample that explains how to do this sorting and explains any key ideas or functions utilized in the code? I appreciate your help.

1

1 Answer 1

-1

You can use the .sort function and pass it a compare function that implements the sorting you'd like to have. The function accepts 2 arguments, the first and second element in the collection to compare. The result of the function should be one of -1 (a is smaller than b), 1 (a is larger than b) or 0 (a and b are equal). The sort function will be called for all elements in the collection until all have been sorted.

books.sort((a, b) => {
  if (a.title < b.title) {
    return -1;
  }
  if (a.title > b.title) {
    return 1;
  }
  return 0;
});

Not the answer you're looking for? Browse other questions tagged or ask your own question.