Sort array of objects by any property value using Javascript

S

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.

Learn about Arrays and Object Properties

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:

[code]
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);
[/code]

Create an array with objects

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.

Sort by value

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.

Sort by property name

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.

[code]
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”));
[/code]

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.

[code]
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”));
[/code]

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.

About the author

By Jamie

My Books