JavaScript Sort Objects by Property

Sorting objects by property is a simple requirement in many JavaScript applications. If you are working on an uncomplicated to-do list or a confusing data-driven application, perceptive how to sort objects based on specific properties is important.

In this article, you are going to learn the sorting of objects by property in JavaScript. We will discuss the different methods, and provide practical examples to help you master this fundamental skill.

Fundamental Concept of JavaScript Sort Methods

Before we discuss the particular sorting objects, let’s briefly cover the fundamental concepts of the JavaScript sort() method.

The sort() method is used to arrange elements of an array in ascending or descending order based on their values.

By default, it sorts elements as strings.

The basic syntax of the sort() method is as follows:

array.sort([exampleValue])

array: The array to be sorted.
exampleValue (optional): An optional callback function that determines the sorting order.

Now that we have shortly overview of the sort() method, let’s explore how to use it to sort objects by property.

JavaScript sort array of objects by property

JavaScript sort array of objects by property, we can offer a custom match function to the sort() method.

This match function will compare the relevant properties of two objects and define their sorting order.

Consider an array of objects that provide different persons:

const person = [
  { name: 'Jude', age: 24 },
  { name: 'Glenn', age: 21 },
  { name: 'Caren', age: 28},
];

function printPersons(personArray) {
  for (let i = 0; i < personArray.length; i++) {
    const { name, age } = personArray[i];
    console.log(`Name: ${name}, Age: ${age}`);
  }
}

printPersons(person);

Sorting by Numeric Property

Assume that you want to sort the people array by the ‘age’ property in ascending order.

We can get this using the following match function:

function sortByAgeAscendingSample(x, y) {
  return x.age - y.age;
}

people.sort(sortByAgeAscending);

The sortByAgeAscendingSample function calculates the difference between the ages of two people, x and y.

If the result is negative, x will come before y, sustaining the ascending order.

Sorting by Alphabetic Property

Furthermore, if you want to sort the person array by the ‘name‘ property in alphabetical order, we can use the following match function:

function sortByNameAscendingSample(x, y) {
  return x.name.localeCompare(y.name);
}

person.sort(sortByNameAscendingSample);

The “sortByNameAscendingSample” function uses the “localeCompare()” function to compare the ‘name‘ property of two objects and arrange them in alphabetical order.

Sorting in Descending Order

To sort objects in descending order, we only need to change the match functions appropriately.

For example, to sort by age in descending order:

function sortByAgeDescendingSample(x, y) {
  return y.age - x.age;
}

person.sort(sortByAgeDescendingSample);

With this match function, the sort() method will arrange the objects in the people array based on the ‘age‘ property in descending order.

Advanced Sorting Methods

Sorting Objects with Nested Properties

Objects may have nested properties that require sorting. Let’s say we have an array of “employees“, and each employee object has a nested ‘employee_name‘ property:

const employees = [
  { position: 'Wev Developer', employee_name: { name: 'Alucard', age: 21 } },
  { position: 'Backend Developer', employee_name: { name: 'Aldous', age: 27 } },
  { position: 'Frontend Developer', employee_name: { name: 'Miya', age: 26 } },
];

To sort the books array based on the ‘name‘ property of the ‘employee_name‘ object, we can change the compare function as follows:

function sortByEmplyoyeeNameAscendingSample(x, y) {
  return x.employee_name.name.localeCompare(y.employee_name.name);
}

employees.sort(sortByEmplyoyeeNameAscendingSample);

Sorting Dates in JavaScript

Sorting objects that include dates can be complex. Let’s say we have an array of “eventsValue“, and each event object has a ‘date‘ property:

const eventsValue= [
  { name: 'Event Baptism', date: new Date('2023-07-26') },
  { name: 'Event Wedding', date: new Date('2023-07-27') },
  { name: 'Event Blessing', date: new Date('2023-07-18') },
];

To sort the “eventsValue” array based on the ‘date‘ property in ascending order, we can use the following match function:

function sortByDateAscendingSample(x, y) {
  return x.date - y.date;
}

eventsValue.sort(sortByDateAscendingSample);

Customizing Sorting with LSI Keywords

In some scenarios, you will need custom sorting that goes above simple comparisons.

LSI (Latent Semantic Indexing) keywords can be used to determine custom sorting orders.

For example, suppose that we have an array of “items“, and each product object has a ‘rating‘ property with values like ‘High‘, ‘Medium‘, and ‘Low‘:

const items = [
  { name: 'Item A', rating: 'Medium' },
  { name: 'Item B', rating: 'Low' },
  { name: 'Item C', rating: 'High' },
];

To sort the “items array based on the ‘rating‘ property using LSI keywords, we can create a custom sorting function as follows:

function sortByRatingCustomSample(x, y) {
  const ratingOrderValue = { 'Low': 1, 'Medium': 2, 'High': 3 };
  return ratingOrderValue[x.rating] - ratingOrderValue[y.rating];
}

items.sort(sortByRatingCustomSample);

In this method, we determine a custom order for the “rating” property using the “ratingOrderValue” object.

FAQs

Can I use the sort() method to sort complex objects?

Yes, you can use the sort() method to sort objects with several properties. By providing a smoother compare function, you can sort complex objects based on different criteria.

How does the localeCompare() method work for string sorting?

The localeCompare() method compares two strings and returns a number showing whether the reference string comes before, after, or is equal to the compared string.

Can I sort an array of objects asynchronously?

Yes, you can sort an array of objects asynchronously using the sort() method in combination with asynchronous compare functions, such as using Promises or async/await.

Conclusion

Sorting objects by property is a fundamental skill in JavaScript programming. Understanding the sort() method and custom compare functions allows you to effectively sort objects based on different criteria.

Additional Resources

Leave a Comment