Sorting means putting things in order. It is needed very often in javascript programs. In this article, we will learn how to sort an array of objects in Javascript based on specific criteria, such as numeric values, strings, or other custom properties. Let’s explore this topic which will help us to effortlessly order data, contributing to code clarity and functionality.
What is an Array of Objects?
An array is a collection of similar kinds of entities i.e. it consists of multiple values in a single variable. So an array of objects simply means multiple objects.
An object consists of key-value pairs where keys represent properties of that object and values denote the actual data of those properties.
Here each object inside the array is a distinct entity with its own set of properties and values.
For Example, consider the following array named workers.
// Array of objects representing worker information
let workers = [
// Object for the first worker
{
firstName: 'Advin',
lastName: 'Mark',
age: 21,
joinDate: 'December 15, 2023'
},
// Object for the second worker
{
firstName: 'Marry',
lastName: 'Con',
age: 23,
joinDate: 'January 20, 2023'
},
// Object for the third worker
{
firstName: 'Harry',
lastName: 'Potter',
age: 32,
joinDate: 'February 25, 2023'
},
// Object for the fourth worker
{
firstName: 'Lily',
lastName: 'Potter',
age: 32,
joinDate: 'June 25, 2023'
}
];
Here an array named workers is declared. It has four objects. Each object has four properties encapsulated within it, namely firstName,lastName, age, and joinDate.
These properties can be accessed using dot notation (object.property) and this property is very important in sorting based on specific criteria.
4 Methods to Sort an Array of Objects in JavaScript
JavaScript has a built-in Sort() method. It naturally sorts in ascending order. It works when we have to sort strings alphabetically. However, this function does not directly work on arrays of numbers or objects.
We must pass a custom compareFunction inside the sort() method to tell how the objects should be compared and ordered. This function defines the criteria for ordering the objects within the array. It is written as:
workers.sort(compareFunction);
This compareFunction takes two parameters in it. Let it be x and y. These are two objects we are comparing. It returns a negative, zero, or positive value based on arguments passed. If ‘x’ should be placed before ‘y’ it returns a negative value, in the case of a positive value ‘x’ is placed after ‘y’, and zero is returned if ‘x’ and ‘y’ are of the same order.
Now let’s explore some examples of numerical, string, and Date values,
1) Sorting By Numeric Values
Let’s take an example that we want to sort worker’s arrays based on age property which is number.
We will use the arrow function which has a much smaller syntax:
// Sorting the 'workers' array based on the 'age' property in ascending order let sortedByAge = workers.sort((x, y) => x.age - y.age);
Here sortedByAge is storing the sorted array. (x, y) => x.age – y.age) this is an arrow function behaving as a compareFunction.
It returns positive, negative, or zero based on the age values of both objects. If x.age-y.age is negative it means ‘x’ is smaller and will come before ‘y’ in sorted order. Similarly, if this is positive it means ‘x’ is bigger than ‘y’ and will come after ‘y’. If the value of both is the same then it will return 0.
Let’s see the results:
// Logging the sorted workers array to the console console.log(sortedByAge);
Output:
[
{
firstName: 'Advin',
lastName: 'Mark',
age: 21,
joinDate: 'December 15, 2023'
},
{
firstName: 'Marry',
lastName: 'Con',
age: 23,
joinDate: 'January 20, 2023'
},
{
firstName: 'Lily',
lastName: 'Potter',
age: 30,
joinDate: 'June 25, 2023'
},
{
firstName: 'Harry',
lastName: 'Potter',
age: 32,
joinDate: 'February 25, 2023'
}
]
As we can see we can sort workers based on the numeric value ‘age’. If we want to sort it in decreasing order we can simply reverse the logic.
// Sorting the 'workers'' array based on the 'age' property in descending order let sortedByAge = workers.sort((x, y) => y.age - x.age);
2) Sorting By String Values
Let’s take the case that we want to sort workers based on firstName in ascending order. We know that while dealing with a simple array with a primitive value like a string we can easily sort it using an array.sort() method without the need for any compareFunction.
But we need to know that this straightforward approach is not applicable when the data we want to sort is nested within a property of objects within the array, rather than the array itself. So we have to manually specify where the string data is located.
Here is an example:
// Using the sort() method with a custom comparison function // Sorting workers by their first names in ascending order sortedByFirstName = workers.sort((x, y) => { // Convert first names to lowercase for case-insensitive sorting let fx = x.firstName.toLowerCase(), fy = y.firstName.toLowerCase(); // Return a negative value if x should be placed before y if (fx < fy) { return -1; } // Return a positive value if x should be placed after y if (fx > fy) { return 1; } // Return 0 if x and y have the same order return 0; }); // 'sortedByFirstName' now contains the worker's array sorted by first names
Here first of all we converted our names into lowercase to ensure case-in-sensitive sorting. Then we returned -1,1 or 0 based on comparisons. More appropriately we returned -1 if ‘x’ should be placed before ‘y’,1 if ‘x’ should be placed after ‘y’, and 0 if no change.
Let’s see the results.
// Logging the sorted workers array to the console console.log(sortedByFirstName);
Output:
[
{
firstName: 'Advin',
lastName: 'Mark',
age: 21,
joinDate: 'December 15, 2023'
},
{
firstName: 'Harry',
lastName: 'Potter',
age: 32,
joinDate: 'February 25, 2023'
},
{
firstName: 'Lily',
lastName: 'Potter',
age: 30,
joinDate: 'June 25, 2023'
},
{
firstName: 'Marry',
lastName: 'Con',
age: 23,
joinDate: 'January 20, 2023'
}
]
So we have sorted workers based on firstNames in ascending order.
3) Sorting By Dates
We have our dates in the form of strings, so first of all we need to convert them into Date objects. After that, the method is similar to comparing two numbers. We will take joinDate strings from each worker, convert them into Date objects, and then use these Date objects for comparison in the sorting process. Let’s see its code:
// Sorting workers based on their joinDate property // Using the sort() method with a custom comparison function sortedByDate = workers.sort((x, y) => { // Convert joinDate strings to Date objects let dateX = new Date(x.joinDate); let dateY = new Date(y.joinDate); // Compare Date objects to achieve ascending sorting return dateX - dateY; }); // 'workers' array is now sorted based on joinDate in ascending order
Here let dateX = new Date(x.joinDate) and let dateY = new Date(y.joinDate); convert the joinDate strings into Date objects.
Let’s see the results:
// Logging the sorted workers array to the console console.log(sortedByDate);
Output:
[
{
firstName: 'Marry',
lastName: 'Con',
age: 23,
joinDate: 'January 20, 2023'
},
{
firstName: 'Harry',
lastName: 'Potter',
age: 32,
joinDate: 'February 25, 2023'
},
{
firstName: 'Lily',
lastName: 'Potter',
age: 30,
joinDate: 'June 25, 2023'
},
{
firstName: 'Advin',
lastName: 'Mark',
age: 21,
joinDate: 'December 15, 2023'
}
]
We have sorted our objects successfully based on dates.
4) Sort Using Multiple Criteria
We can also sort by taking into consideration multiple properties. For example, we can sort based on last name in ascending order, but what if we have the same last name of two workers? Then we can consider the first name of the workers. By this, we are considering multiple properties of workers.
Here also we will first of all convert into lowercase for case in-sensitive sort. After that we will compare last names and return 1 or -1; if last names are the same, we will move to first names with similar logic. See an example below:
sortedByName = workers.sort((x, y) => { // Convert last names and first names to lowercase for case-insensitive sorting let lastNameX = x.lastName.toLowerCase(); let lastNameY = y.lastName.toLowerCase(); let firstNameX = x.firstName.toLowerCase(); let firstNameY = y.firstName.toLowerCase(); // Compare last names if (lastNameX < lastNameY) { return -1; } if (lastNameX > lastNameY) { return 1; } // If last names are equal, compare first names if (firstNameX < firstNameY) { return -1; } if (firstNameX > firstNameY) { return 1; } // If both last names and first names are equal, return 0 return 0; });
Let’s see the results:
// Logging the sorted workers array to the console console.log(sortedByName);
Output:
[
{
firstName: 'Marry',
lastName: 'Con',
age: 23,
joinDate: 'January 20, 2023'
},
{
firstName: 'Advin',
lastName: 'Mark',
age: 21,
joinDate: 'December 15, 2023'
},
{
firstName: 'Harry',
lastName: 'Potter',
age: 32,
joinDate: 'February 25, 2023'
},
{
firstName: 'Lily',
lastName: 'Potter',
age: 30,
joinDate: 'June 25, 2023'
}
]
We can see that we have sorted based on lastName first and in the case where both the lastName were the same we have sorted considering the firstName.
Now you can move on to empty an array in JavaScript.
Conclusion
Sorting an array of objects is a fundamental operation for any developer. By utilizing the sort() method and providing a custom comparison function we were able to arrange the array of objects based on specific needs. We discussed different ways of sorting like by numeric values, strings, and dates.