Scott Andrew - lo-fi acoustic pop superhero!

Join the Demo Club to unlock new music, get discounts, tour dates and other neato stuff:

or learn more here.

March 8, 2002

Sorting JavaScript Arrays by Property

A new addition to the JavaScript Junkyard: sortByProperty(). This is actually an extension to the JavaScript Array object which enables you to sort the array order based on a specific property of each array element, instead of just the element itself. It also allows you to sort in reverse order.

The array object already has a handy sort() method that rearranges the array elements in lexicographic (”dictionary”) order by default. This is fine for one-to-one mappings, where each element contains one exactly one value. But I often use arrays to store similar objects with similar properties, much like a recordset. here I need something to examine a particular property of each element and used that value to determine the sort order. For example, if each element contains a “car” object with make, model and year properties, I may need to find a way to sort the array based on the value of “year.”

What is usually overlooked is that you can hand the sort() method one argument: a comparative function that affects the logic of the sorting. You can read more about the comparative function of sort() here — the general idea is that the sort() method hands two elements to the comparative function and says “here, compare these” and the comparative function says “okay then” and returns a result that tells sort() where to place the elements in the array.

So given this information, it’s pretty easy to build a function that takes two elements, looks for a specifically named property on each and compares the values to determine the sort order. For example, to sort an array of “car” objects by model, we can build something like this:


function compare(a, b) {
  if (a.model < b.model)
  {
    return -1;
  }
  if (a.model > b.model)
  {
    return 1;
  }
  return 0;
}

Then we can do the sort like so:

cars.sort(compare);

Here’s the kicker: the array object also has a reverse() method, that reverses the order of elements in an array. However, reverse() doesn’t do any sorting at all. So what if I want to sort my cars array by model, but in reverse order? The easiest way is to modify the logic in the compare() function to return the opposite values:


if (a.model < b.model)
{
  return 1;
}
if (a.model > b.model)
{
  return -1;
}

So now all I need is to write a custom sorting function that allows me take advantage of the native sort() method of arrays and lets me specify the property name to sort on and the direction (forward or reverse) of the sorting. Here’s the completed function:


function _sortByProperty(property,rev)
{
  var fn = function(a,b)
  {
    if (a[property] < b[property])
    {
      return (rev)? 1:-1;
    } else if (a[property] > b[property])
    {
      return (rev)? -1:1;
    } else
    {
      return 0;
    }
  }
  this.sort(fn);
  return this;
}

Array.prototype.sortByProperty = _sortByProperty;

Now to sort an array of objects by property, just call the sortByProperty() method of the array:

cars.sortByProperty("model");

To do a reverse sort, pass true as a second argument:

cars.sortByProperty("year",true);

You can see the sortByProperty() method in action here. Here’s the array containing the objects:


var pets = [];
pets[pets.length] = {name:”Fido”,animal:”dog”};
pets[pets.length] = {name:”Scratchy”,animal:”cat”};
pets[pets.length] = {name:”Bubbles”,animal:”chimp”};
pets[pets.length] = {name:”Pooyan”,animal:”pig”};
pets[pets.length] = {name:”Donald”,animal:”duck”};



This script has also been moved to the JavaScript Junkyard.

No Comments

Leave a Comment

Close
  • E-mail
  • Social Web

Email this page to a friend:

E-mail It

Buy Music

Download Scott Andrew tracks from iTunes Find Scott Andrew at Rhapsody Find Scott Andrew at Amazon Find Scott 
Andrew at CD Baby

New Videos

More Videos

Photos

More Photos at Flickr

Recent Reader Comments

  • michael: Well ain't that a hoot! A couple midwesterners tur...
  • big daddy d: still can't beat the andrew, spaly, jolin "Peace o...
  • big daddy d: good room sound. would you play their again?
  • big daddy d: hey he's driving on the wrong side of the road.
  • state shirt: yes you can!