JavaScript Array of Objects Sorting: How to Sort by a Specific Object Property

12299
2
09-18-2023 03:46 AM
hectorsalamanca
New Contributor III

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, 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.

Tags (1)
0 Kudos
2 Replies
Sage_Wall
Esri Contributor

Hi @hectorsalamanca , take a look at this website for the full explanation but below is a code snippet that should sort your array of objects.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#sorting_...

 

// sort by title
books.sort((a, b) => {
  const titleA = a.title.toUpperCase(); // ignore upper and lowercase
  const titleB = b.title.toUpperCase(); // ignore upper and lowercase
  if (titleA < titleB) {
    return -1;
  }
  if (titleA > titleB) {
    return 1;
  }

  // names must be equal
  return 0;
});

 

0 Kudos
KenBuja
MVP Esteemed Contributor

You have to use the array.sort method, using a compare function to define the sort order. Take a look at this section of the documentation that explains different ways of sorting arrays of objects. In this example, a simpler sort function uses the locateCompare method to return the sorted titles.

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 }
];
books.sort(function(a, b) {
  return a.title.localeCompare(b.title);
});

books.forEach((book) => console.log(book.title));

 

0 Kudos