Javascript contains a built-in array method to sort simple arrays. But I rarely am using simple JavaScript arrays, typically the elements inside my array a complex objects with many different properties. A simple example is a person that perhaps contains a first name, last name, and age. I can see myself wanting to sort by any one of those properties. So how can I sort a JavaScript array that contains complex objects and better yet, not hard-coded and dynamically by any property of my object.
An array is a collection of objects. You can think of an array as a list of things. It's similar to a spreadsheet where each row represents one object and each column represents a property of that object. Let's begin by looking at a hard-coded solution to sort my array by last name ascending: To create an array, use the new operator to declare a variable called myArray. Then, add some objects to the array using the push method. Leveraging the sort function, I've told Javascript to call my custom compare function. As you can see this accesses the lastName properties and compares which is greater or less than. You can also sort arrays by value with the sort() method. This method sorts the elements of an array in ascending order based on the values of each element. Perfect, now how do we make this dynamic? Be sure while doing this you don't encounter the problem Solving No Access-Control-Allow-Origin with Node js and Express. If you need to sort an array by multiple properties, use the sort() method with a callback function. The callback function receives two arguments: the first argument is the current object being considered, and the second argument is the next object to consider. This time, I've wrapped the innards of the previously created compare function inside a function called sortByProperty that accepts the property to sort on. And finally, let's really take this to the next level. Let's also support the capabilities of choosing Ascending or Descending! At the same time, I'll add this an Array prototype to simplify calling this function. Here is the final result and example usage of the new Array function sortByProperty. By adding a - character at the start of the property name it will inverse the sort order providing even more dynamic capabilities of sorting an array of objects by a specific property using Javascript. Published on Jun 17, 2022 Tags: JavaScript
| Javascript Arrays Tutorial
| sort
Did you enjoy this article? If you did here are some more articles that I thought you will enjoy as they are very similar to the article
that you just finished reading.
No matter the programming language you're looking to learn, I've hopefully compiled an incredible set of tutorials for you to learn; whether you are beginner
or an expert, there is something for everyone to learn. Each topic I go in-depth and provide many examples throughout. I can't wait for you to dig in
and improve your skillset with any of the tutorials below.
Learn about Arrays and Object Properties
var myCustomers = [
{
"firstName": "Bob",
"lastName": "Smith",
"age": 21
}, {
"firstName": "Johnny",
"lastName": "Ace",
"age": 21
}
];
function compare(a, b) {
if (a.lastName > b.lastName) return 1;
if (a.lastName < b.lastName) return -1;
return 0;
};
myCustomers.sort(compare);
console.log(myCustomers);
Create an array with objects
Sort by value
Sort by property name
function sortByProperty(property) {
return function (a, b) {
if (a[property] > b[property]) return 1;
if (a[property] < b[property]) return -1;
return 0;
}
};
myCustomers.sort(sortByProperty("lastName"));
Array.prototype.sortByProperty = function() {
function _sortByproperty(property) {
var sortOrder = 1;
if (property[0] == "-") {
sortOrder = -1;
property = property.substr(1);
}
return function(a, b) {
var result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0;
return result * sortOrder;
}
}
function _getSortFunc() {
if (arguments.length == 0) {
throw "You must provide a property to sort by for Array.sortByProperty()";
}
return function(a, b) {
for (var result = 0, i = 0; result == 0 && i < arguments.length; i++) {
result = _sortByproperty(arguments[i])(a, b);
}
return result;
}
}
return this.sort(_getSortFunc.apply(null, arguments));
}
// Ascending
console.log(myCustomers.sortByProperty("lastName"));
// Descending
console.log(myCustomers.sortByProperty("-lastName"));
Related Posts
Tutorials
Learn how to code in HTML, CSS, JavaScript, Python, Ruby, PHP, Java, C#, SQL, and more.