Follow @endyourif rss Facebook LinkedIn

Sort array of objects by any property value using Javascript Sort array of objects by any property value using Javascript

Published on Jun 17, 2022

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.



Let's begin by looking at a hard-coded solution to sort my array by last name ascending:


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);


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.

Perfect, now how do we make this dynamic?


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"));


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.


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"));


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.

Tags: JavaScript | Javascript Arrays Tutorial | sort

My Books
ASP.NET MVC 5 With Bootstrap and Knockout.js
Knockout.js Building Dynamic Client-Side Applications
20 Recipes for Programming MVC 3
20 Recipes for Programming PhoneGap
Rapid Application Development with CakePHP