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?

2

2 Answers 2

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]}
}));

Sign up to request clarification or add additional context in comments.

1 Comment

What does return obj[b] - obj[a] mean? Is that a subtract operator... why would sort return a difference of two numeric values? Shouldn't it return an object?
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; }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.