简体   繁体   中英

Sort key-value pairs descending based on property value

I built a K/V pair array based on some values.

Here is the data structure:

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
});

How can I sort selItemsDimArray numerically(lowest to highest) based on element.x property?

The 'much-loved' W3schools gives me an example of:

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

Simply like this:

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

解决方案selItemsDimArray.sort(function(a,b){return ax-bx});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM