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




我有一个对象,该对象具有称为z的属性:

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


假设我创建了该对象的3个实例:

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


然后将这些实例放入数组中

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


问题

如何根据升序包含的对象的z属性对该数组排序?
排序后的最终结果应为:

before -> buildings = [a, b, c]
sort - > buildings.sort(fu)
after -> buildings = [b, a, c]

最佳答案

您可以将比较函数传递给.sort()

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


然后使用:

myarray.sort(compare)


这是一些docs

07-24 18:46