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

Sort key-value pairs descending based on property value

本文关键字:降序 排序 键值对 属性      更新时间:2023-09-26

我基于一些值构建了一个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属性?

"备受喜爱"的W3学校给了我一个例子:

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

简单如下:

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在MDN上

解决方案selItemsDimArray.sort(函数(a,b){return a.x-b.x});