可能重复:
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 属性对此数组 IN ASCENDING ORDER 进行排序? 排序后的最终结果应为:
before -> buildings = [a, b, c]
sort - > buildings.sort(fu)
after -> buildings = [b, a, c]
答案 0 :(得分:5)
您可以将比较函数传递给.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