0

I have an JavaScript object:

var objs = {'1':2, '2':3, '3':1, '4':2};

How can I sort the properties by the value of numbers in JavaScript?

I know about sort(a,b), but that only seems to work on strings and numbers. Do I need to add a toString() method to my objects?

7
  • 4
    objs is array or object? Commented Jun 18, 2020 at 11:35
  • 2
    please add the array. Commented Jun 18, 2020 at 11:36
  • sorry i mean objs is object Commented Jun 18, 2020 at 11:47
  • AFAIK you can't sort object properties. Commented Jun 18, 2020 at 11:50
  • 1
    @evolutionxbox, you can with a new object, but not index like values. Commented Jun 18, 2020 at 11:51

1 Answer 1

1

An object does not (always) follow the insertion order. So it can't be guaranty that you always get same output. For sorting you can use either array or Map to maintain the order. For more info please see stackoverflow discussion.

According to question: var objs = {'1':2, '2':3, '3':1, '4':2}; How can I sort them by the value of numbers in JavaScript? You can do as follows

var objs = {
  '1': 2,
  '2': 3,
  '3': 1,
  '4': 2
};
var map = new Map(Object.entries(objs));
var sorted = new Map(Array.from(map).sort((a, b) => a[1] - b[1]));
console.log(sorted);
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.