0

I have this structure:

var example=[0,{ "3":4 , "6":1 , "11":2 }];

I would like to transform this into

[0,{ "6":1 , "11":2 , "3":4 }]

based on the number on the right (ascendant): 4, 1, 2 becomes 1 ,2, 4.

Dhia
  • 10,119
  • 11
  • 58
  • 69
bob dylan
  • 989
  • 2
  • 10
  • 26
  • 2
    You can't, objects are not sortable. – Teemu Dec 12 '15 at 08:50
  • Technically you can't, but it seems like most browser implementations will iterate them in the order in which they were added to the object. – Evan Trimboli Dec 12 '15 at 08:56
  • @EvanTrimboli You can't trust on that, ["The mechanics and order of enumerating the properties is not specified"](http://es5.github.io/#x12.6.4). – Teemu Dec 12 '15 at 09:03
  • Yes, I know. That's why I said "technically you can't, but practically you pretty much can". – Evan Trimboli Dec 12 '15 at 09:04
  • 2
    If you want things in a particular order, use an array, not a plain object to store them. It's way, way, way easier to order things in an array. While it can technically be done with a plain object in a modern browser, it's a major hassle and very prone to mistakes and hard to reorder things without creating an entirely new object. – jfriend00 Dec 12 '15 at 09:25

1 Answers1

0

Infact order in objects are not guaranteed in JavaScript, you need to use an Array to have similar result:

function sortObjectByValue(obj) {
    var result = [];
    var key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) {
            arr.push({
                'key': key,
                'value': obj[key]
            });
         }
    }
    arr.sort(function(a, b) {
        return a.value - b.value;
    });
    return result; // returns array
}

>>>var obj = { "3":4 , "6":1 , "11":2 };
>>>console.log(sortObjectByValue(obj))
//[Object { key="6",  value=1}, Object { key="11",  value=2}, Object { key="3",  value=4}]

I will suggest also if you find your self dealing a lot with data-structure and need advanced methods check Underscore

Dhia
  • 10,119
  • 11
  • 58
  • 69