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] 
0

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.