0

So here's the object:

Object structure

As you can see, the last amount(2000) is lower than 10000 but it's still at the end. I'm trying to display the elements sorted by amount. I know that I have to convert the object to array and use sort on it, but don't have an idea how can I do this properly.

EDIT: I've tried something like this without any success:

var packs_array = [];

jQuery.each(json.purchase_packs, function(i, pack) {
    packs_array.push(pack);
});

packs_array.sort();
user1410644
  • 351
  • 4
  • 6
  • 15

3 Answers3

1

To do this, you need to convert your object into an array first...

var arr = $.map(json.purchase_packs, function(v) { return v; });

... then sort this array with a custom sorter function:

arr.sort(function(a, b) {
  return a.amount - b.amount;
});

Demo. Note that sorting is in-place operation (i.e., arr.sort alters an existing object).

raina77ow
  • 103,633
  • 15
  • 192
  • 229
1
var packs = {
    0: { amount: 2000 },
    3: { amount: 1000 },
    5: { amount: 50 }
};

var sortedPacks = Object.keys(packs)
    .map(function (id)  {
        packs[id].id = parseInt(id, 10);
        return packs[id];
    })
    .sort(function (a, b) {
        return a.amount - b.amount;
    });

console.log(sortedPacks); // => [{"amount":50,"id":5},{"amount":1000,"id":3},{"amount":2000,"id":0}]
FloHimself
  • 291
  • 3
  • 12
  • Note: This snipped uses ES5 features. If you are targeting browsers like IE8 and earlier, you should include a ES5 shim like [Augment.js](http://augmentjs.com/) or [es5-shim.js](https://github.com/kriskowal/es5-shim) in your page. – FloHimself Dec 18 '13 at 12:41
-1

JavaScript sort() function works with list elements as strings by default. You should specify sort function to sort other value types:

var l = [1, 5, 12, 127, 12, 3, 9];
l.sort(function(a,b){return a-b});
=> [ 1, 3, 5, 9, 12, 12, 127 ]

Source

archydragon
  • 139
  • 3