nicholaswmin
nicholaswmin

Reputation: 22949

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?

Upvotes: 0

Views: 42

Answers (2)

Wrapper Tech
Wrapper Tech

Reputation: 282

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

Upvotes: 1

Salman Arshad
Salman Arshad

Reputation: 272106

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

Upvotes: 2

Related Questions