Sorting data is a common task in programming and isn’t an exception in Javascript. In this article, we will discuss how to sort an array of objects by their property values in 2 different ways: the first one is to write code from scratch and the second one is to make use of a third-party library. Without any further ado, let’s get started.
Writing Code from Scratch
A Quick Note about the sort() Method
We can use the Javascript built-in sort() method to sort an array of objects by their property value. The sort() method takes a callback function that defines how the elements in the array should be compared. The callback function takes 2 parameters, the two elements being compared, and returns a number. If the number is less than 0, the first element should be before the second element in the sorted array. If the number is greater than 0, the second element should be before the first element in the sorted array.
sort(obj1, obj2) {
if (obj1.propertyName < obj2.propertyName) {
return -1;
}
if (obj1.propertyName > obj2.propertyName) {
return 1;
}
return 0;
}
Creating a Function to Sort Arrays of Objects
We will create a reusable function that can take 3 parameters: an array of objects, a property name, and the order (ascending or descending). The function will loop through the input array and compare each object’s property value. If the property value of the first object is greater than the property value of the second object, then the first object should be before the second object in the sorted array. Otherwise, the second object should be before the first object in the sorted array.
if the order is ascending, they will return the sorted array immediately. If the order is descending, we will return a reversed sorted array.
Here’s the function we’re talking about, and you can reuse it in many projects as you want:
const sortArrayOfObjects = (arr, propertyName, order = 'ascending') => {
const sortedArr = arr.sort((a, b) => {
if (a[propertyName] < b[propertyName]) {
return -1;
}
if (a[propertyName] > b[propertyName]) {
return 1;
}
return 0;
});
if (order === 'descending') {
return sortedArr.reverse();
}
return sortedArr;
};
Let’s try our function in a popular real-world example.
Example
Sorting Products By Price
Sort by price from low to high:
const products = [
{ name: "Product 1", price: 100 },
{ name: "Product 2", price: 50 },
{ name: "Product 3", price: 150 },
{ name: "Product 4", price: 200 },
]
const sortedProducts = sortArrayOfObjects(products, "price");
console.log(sortedProducts);
Output:
[
{ name: 'Product 2', price: 50 },
{ name: 'Product 1', price: 100 },
{ name: 'Product 3', price: 150 },
{ name: 'Product 4', price: 200 }
]
Sort by price from high to low:
const products = [
{ name: 'Product 1', price: 100 },
{ name: 'Product 2', price: 50 },
{ name: 'Product 3', price: 150 },
{ name: 'Product 4', price: 200 },
];
const sortedProducts = sortArrayOfObjects(products, 'price', 'descending');
console.log(sortedProducts);
Output:
[
{ name: 'Product 4', price: 200 },
{ name: 'Product 3', price: 150 },
{ name: 'Product 1', price: 100 },
{ name: 'Product 2', price: 50 }
]
Using Lodash
Another way to sort an array of objects by their property value is to use the sortBy() method from the Lodash library. This method takes an array of objects and a property name and returns an array of objects sorted by the specified property.
You can install Lodash via npm:
npm i lodash
Example:
import _ from 'lodash';
const employees = [
{ name: 'John', dateOfBirth: '1980-01-01', salary: 1000 },
{ name: 'Jack', dateOfBirth: '1990-01-01', salary: 3000 },
{ name: 'Jane', dateOfBirth: '1985-01-01', salary: 2000 },
];
// Sort by dateOfBirth
const sortedEmployees = _.sortBy(employees, 'dateOfBirth');
console.log(sortedEmployees);
Output:
[
{ name: 'John', dateOfBirth: '1980-01-01', salary: 1000 },
{ name: 'Jane', dateOfBirth: '1985-01-01', salary: 2000 },
{ name: 'Jack', dateOfBirth: '1990-01-01', salary: 3000 }
]
Best Practices for Sorting Arrays of Objects
When sorting an array of objects, it is important to consider performance.
Performance is important because sorting large arrays can be time-consuming and resource-intensive. If your arrays are small, there will be no significant difference between Javascript’s native sort() and Lodash’s sortBy(). However, when your arrays range from large to very large, using the Javascript native sort() method will be faster and give better performance.
If you load data from a database like PostgreSQL, MySQL, etc, then you can sort the results with your SQL queries without having to do it again in Javascript.
Conclusion
Through this article, you learned how to sort an array of objects by their property value. You can do it just by using the sort() method of vanilla Javascript, as well as the convenient sortBy() method from a popular third-party library named Lodash. The choice is totally depends on your needs.