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?

evolutionxbox
  • 3,932
  • 6
  • 34
  • 51

1 Answers1

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);
arif
  • 524
  • 8
  • 18
Shuvojit Saha
  • 382
  • 2
  • 11