根据属性值对键值对进行降序排序

时间:2014-09-06 09:46:13

标签: javascript arrays sorting

我根据一些值建立了一个K / V对数组。

以下是数据结构:

var selItemsDimArray = []

selItemsDimArray.push({
    'examinedElem': multiselected[i],
    'x': bb.x,
    'y': bb.y,
    'x2': (bb.x + bb.width),
    'y2': (bb.y + bb.height),
    'height': bb.height,
    'width': bb.width
});
  

如何基于数字(从最低到最高)对selItemsDimArray进行排序   在element.x属性?

“备受喜爱”的W3schools给了我一个例子:

var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a-b}); //Where did a and b come from?

2 个答案:

答案 0 :(得分:2)

就像这样:

selItemsDimArray.sort(function(a, b) {
    // here a and b are two items from selItemsDimArray array
    // which means it is possible access and compare the x property for both items
    return a.x - b.x;
});

Array.prototype.sort on MDN

答案 1 :(得分:1)

解 selItemsDimArray.sort(function(a,b){return a.x-b.x});