2

I have an object like:

json_result = {X: 0.42498, A: 0.34891, B: 0.38408, C: 0.22523}

I want to sort the above in descending order of values, i.e.,

json_result = {X: 0.42498, B: 0.38408, A: 0.34891, C: 0.22523}

I am thinking something like:

for ( key in json_result)
{
    for ( value1 in json_result[key])
  {
    for (value2 in json_result[key])
    {

    }
  }
}

Is there any other way around?

Heretic Monkey
  • 10,498
  • 6
  • 45
  • 102
learner
  • 3,560
  • 3
  • 42
  • 87

2 Answers2

3

As mentioned in the comments, object key order isn't guaranteed, so sorting your object wouldn't make much sense. You should use an Array as a result.

var json_result = {X: 0.42498, A: 0.34891, B: 0.38408, C: 0.22523};


function sort(obj) {
  return Object.keys(obj).sort(function(a, b) {
    return obj[b] - obj[a];
  });
}

var sorted = sort(json_result);
console.log('sorted keys', sorted);

console.log('key lookup', sorted.map(function(key) { 
  return json_result[key]
}));

console.log('sorted objects', sorted.map(function(key) { 
  return {[key]: json_result[key]}
}));
cyr_x
  • 12,554
  • 2
  • 26
  • 42
2

You can't "sort" the keys of an object, because they do not have a defined order. Think of objects as a set of key-value pairs, rather than a list of them.

You can, however, turn your JSON into a sorted list (array) of key-value pairs, yielding an object that looks like this:

[ ['X', 0.42498], ['B', 0.38408], ['A', 0.34891], ['C', 0.22523] ]

Demo:

var result = {X: 0.42498, A: 0.34891, B: 0.38408, C: 0.22523}

var sorted = Object.keys(result).map(function (key) {
  return [key, this[key]]
}, result).sort(function (a, b) {
  return b[1] - a[1]
})

console.log(sorted)
.as-console-wrapper { min-height: 100vh; }
gyre
  • 14,437
  • 1
  • 32
  • 46