1

Possible Duplicate:
Sort JavaScript array of Objects based on one of the object’s properties

I have an object which has a property called z:

function building(z)
{
  this.z = z;
}

Let's say I create 3 instances of this object:

a = new building(5)
b = new building(2)
c = new building(8)

These instances are then placed into an array

buildings = []
buildings.push(a)
buildings.push(b)
buildings.push(c)

The Question

How would I sort this array IN ASCENDING ORDER based on the z property of the objects it contains? The end result after sorting should be:

before -> buildings = [a, b, c] 
sort - > buildings.sort(fu)
after -> buildings = [b, a, c] 
Community
  • 1
  • 1
Jamie Fearon
  • 2,574
  • 13
  • 47
  • 65

1 Answers1

5

you can pass a compare-function to .sort()

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

then use:

myarray.sort(compare)

here are some docs

lrsjng
  • 2,615
  • 1
  • 19
  • 23
  • I'm aware of this but the question I have is what would the compare function be? I'm new to using compare functions so would appreciate some help. – Jamie Fearon Oct 28 '12 at 13:14