Thanh Dao
Thanh Dao

Reputation: 1260

Sort numeric keys in object

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!

Upvotes: 1

Views: 842

Answers (2)

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

Upvotes: 0

Yangguang
Yangguang

Reputation: 1785

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

Upvotes: 4

Related Questions