1

I have an object with keys and values are integer:

{
  10: 3,
  20: 3,
  30: 3,
  60: 1
}

I want to sort this object as

{
  60: 1,
  30: 3,
  20: 3,
  10: 3
}

Are you have any solutions to solve my problems?

Sorry for my bad English!

Thanh Dao
  • 1,218
  • 2
  • 16
  • 43
  • You want to sort by values ? Anyway check the javascript library [underscore](http://underscorejs.org/) method sortBy – Max May 16 '15 at 10:35
  • Javascript doesn't make any guarantees about property order, so you can't "sort" the object. You could *display* it in that order, but you can't sort the properties inside the object, at least in any cross-browser-compatible way. – CupawnTae May 16 '15 at 10:36
  • Refer to this question: http://stackoverflow.com/questions/1069666/sorting-javascript-object-by-property-value – Tarun Dugar May 16 '15 at 10:41

2 Answers2

4

4.3.3 Object An object is a member of the type Object. It is an unordered collection of properties each of which contains a primitive value, object, or function. A function stored in a property of an object is called a method.

see Standard ECMA-262

Yangguang
  • 1,785
  • 9
  • 10
0

I´ve prepared a little solution for you. Converting it first to an array, and then sorting by the property you need.

Also showing in the print the difference between objects {} and arrays []. Check the fiddle, there you have a sorted array with the values from you object.

var obj = {
  10: 3,
  20: 3,
  30: 3,
  60: 1
};
var keys = Object.keys(obj);

var arr = [];

for (i = 0; i < keys.length; i++) {
  arr.push({
    val: obj[keys[i]],
    key: keys[i]
  });

}

var ordered = false;

while (!ordered) {
  var i = 0;
  ordered = true;
  for (i = 0; i < arr.length - 1; i++) {
    if (arr[i].val > arr[i + 1].val) {
      var pass = arr[i + 1].val;
      var passkey = arr[i + 1].key;
      arr[i + 1].val = arr[i].val;
      arr[i + 1].key = arr[i].key;
      arr[i].val = pass;
      arr[i].key = passkey;

      ordered = false;
    }

  }

}

var newObj = {};
for (i = 0; i < arr.length; i++) {
  newObj[arr[i].key] = arr[i].val
  console.log("val:" + arr[i].val + ",key:" + arr[i].key);
}

document.write("<p>THE ARRAY:" + JSON.stringify(arr) + "</p>");

document.write("<p>THE OBJECT:" + JSON.stringify(newObj) + "</p>");