8

How can I convert this js object

 var obj1 =  {"user1":28, "user2":87, "user3":56};

into a string array, sorted by value, like so:

["user2","user3","user1"]
3
  • 2
    var sortedKeys = Object.keys(obj1).sort(); in modern browsers. Commented May 25, 2015 at 14:41
  • 2
    @Pointy will that not sort the keys by their name and not their value? Commented May 25, 2015 at 14:44
  • @Luke oh oh I see; right, the .sort() would need a comparator for that. Commented May 25, 2015 at 15:04

1 Answer 1

10

Use this:

var obj1 =  {"user1":28, "user2":87, "user3":56};
var a = Object.keys(obj1).sort(function(x,y){return obj1[y]-obj1[x]})
console.log(a);

Output:

["user2", "user3", "user1"]
Sign up to request clarification or add additional context in comments.

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.